Task

Take a   Natural Number   in a given base and return the sum of its digits:

   110         sums to   1
   123410   sums to   10
   fe16       sums to   29
   f0e16     sums to   29


 
(* ****** ****** *)
//
// How to compile:
// patscc -DATS_MEMALLOC_LIBC -o SumDigits SumDigits.dats
//
(* ****** ****** *)
//
#include
"share/atspre_staload.hats"
//
(* ****** ****** *)
 
extern
fun{a:t@ype}
SumDigits(n: a, base: int): a
 
implement
{a}(*tmp*)
SumDigits(n, base) = let
//
val base = gnumber_int(base)
//
fun
loop (n: a, res: a): a =
  if gisgtz_val<a> (n)
    then loop (gdiv_val<a>(n, base), gadd_val<a>(res, gmod_val<a>(n, base)))
    else res
//
in
  loop (n, gnumber_int(0))
end // end of [SumDigits]
 
(* ****** ****** *)
 
val SumDigits_int = SumDigits<int>
 
(* ****** ****** *)
 
implement
main0 () =
{
//
val n = 1
val () = println! ("SumDigits(1, 10) = ", SumDigits_int(n, 10))
val n = 12345
val () = println! ("SumDigits(12345, 10) = ", SumDigits_int(n, 10))
val n = 123045
val () = println! ("SumDigits(123045, 10) = ", SumDigits_int(n, 10))
val n = 0xfe
val () = println! ("SumDigits(0xfe, 16) = ", SumDigits_int(n, 16))
val n = 0xf0e
val () = println! ("SumDigits(0xf0e, 16) = ", SumDigits_int(n, 16))
//
} (* end of [main0] *)
 