(* sample.ml CS 313 Example ML functions To load this file from within sml, type use "sample.ml"; To run ML on this file, use sml < sample.ml *) (***** list functions *****) (* sum the numbers in a list *) fun sumlist1 l = if null l then 0 else hd(l) + sumlist1 (tl(l)); (* same function, defined using cases *) fun sumlist2 [] = 0 (* No semicolon here!! *) | sumlist2 (a::y) = a + sumlist2 y; (* sum the numbers in a list - tail-recursive version *) fun sumlist3 l = let fun sumiter(x, res) = if null x then res else sumiter(tl(x), hd(x) + res) in sumiter(l, 0) end; (* same function, helper function defined using cases *) fun sumlist4 l = let fun sumiter([], res) = res | sumiter(n::y, res) = sumiter(y, n+res) in sumiter(l, 0) end; (* sample output: (only for sumlist1 here - the others work too :) - sumlist1 []; val it = 0 : int - sumlist1 [1, 2, 3, 4]; val it = 10 : int *) (***** binary search tree *****) (* type definition *) datatype bst = Empty | Node of int * bst * bst; (* useful function to create a leaf node *) fun leaf n = Node(n, Empty, Empty); (* compute the height of a tree *) fun height Empty = 0 | height (Node(n, left, right)) = 1 + Int.max(height left, height right); (* sample output: - height Empty; val it = 0 : int - height(leaf 4); val it = 1 : int - height (Node(3, leaf(2), Empty)); val it = 2 : int - val t = Node(3, Node(1, Empty, leaf(2)), leaf(4)); val t = Node (3,Node (1,Empty,Node #),Node (4,Empty,Empty)) : bst - height t; val it = 3 : int *)