// // Author: Hongwei Xi (hwxi AT cs DOT bu DOT edu) // Time: September, 2008 // // // tally-2008-09-04.dats: // tally (n) = 0 + 1 + ... + n // // // How to compile: // atscc -o tally tally-2008-09-04.dats // extern fun tally (n: int): int (* // non-tail-recursive implement tally (n) = begin if n > 0 then n + tally (n-1) else 0 end // end of [tally] *) // tail-recursive implement tally (n) = let fun loop (n: int, i: int, res: int): int = if i <= n then loop (n, i+1, res+i) else res in loop (n, 0, 0) end // end of [tally] (* ****** ****** *) // [main] is already declared elsewhere implement main (argc, argv) = let val () = if (argc >= 2) then () else begin prerrf ("Usage: %s [integer]", @(argv.[0])); prerr_newline () end val () = assert (argc >= 2) val arg1 = argv.[1] val n = int_of_string (arg1) in printf ("tally (%i) = %i\n", @(n, tally n)) end // end of [main] (* ****** ****** *) (* end of [tally-2008-09-04.dats] *)