(*
** Course: Concepts of Programming Languages (BU CAS CS 320)
** Semester: Summer I, 2009
** Instructor: Hongwei Xi (hwxi AT cs DOT bu DOT edu)
*)

//
// Author: Hongwei Xi (hwxi AT cs DOT bu DOT edu)
//

(* ****** ****** *)

// The "hello, world!" example in ATS

implement main () = begin
  print_string "Hello, world!"; print_newline ()
end (* end of [main] *)

(* ****** ****** *)

// [gcd] for computing the gcd of two given natural numbers
extern fun gcd (x: int, y: int): int // int gcd (int x, int y) ;

implement gcd (x, y) =
  if y = 0 then x else gcd (y, x mod y)
// end of [gcd]

(* ****** ****** *)

#define PI 3.1415927

extern fun disk_area_radius (radius: double): double

implement disk_area_radius (r) = PI * r * r

(* ****** ****** *)

//
// tuples and records
//

val x = 10
val y = 20

val xy = '(x, y) // field names: 0 and 1

val xy0 = xy.0
val xy1 = xy.1

val xy = '{
  fst= x, snd= y
} // end of [val]

val xy_fst = xy.fst
val xy_snd = xy.snd

val sum = xy.fst + xy.snd

(* ****** ****** *)

extern fun sum1 (n: int): int
extern fun sum2 (n: int): int

// non-tail-recursive implementation
implement sum1 (n) =
  if n > 0 then n + sum1 (n-1) else 0

// tail-recursive implementation
implement sum2 (n) = let
  // a typical functional loop
  fun loop (n: int, res: int): int =
    if n > 0 then loop (n-1, n + res) else res
  // end of [loop]
in
  loop (n, 0)
end // end of [sum2]

(* ****** ****** *)

(* end of [code-2009-05-19.dats] *)