Title here
Summary here
Here we use range to sum the numbers in a list. Arrays in Standard ML work similarly.
val nums = [2, 3, 4]
val sum = foldl (op +) 0 nums
val () = print ("sum: " ^ Int.toString(sum) ^ "\n")range on arrays and lists provides both the index and value for each entry. In the first example, we didn’t need the index, so we ignored it. Sometimes we actually want the indexes though.
val _ = List.app (fn (i, num) => if num = 3 then print ("index: " ^ Int.toString(i) ^ "\n") else ()) (ListPair.zip (List.tabulate (List.length nums) (fn x => x), nums))range on map iterates over key/value pairs. In Standard ML, we use a list of tuples to represent key-value mappings.
val kvs = [("a", "apple"), ("b", "banana")]
val _ = List.app (fn (k, v) => print (k ^ " -> " ^ v ^ "\n")) kvsrange can also iterate over just the keys of a map.
val _ = List.app (fn (k, _) => print ("key: " ^ k ^ "\n")) kvsrange on strings iterates over Unicode code points. The first value is the starting byte index of the rune and the second the rune itself.
val str = "go"
val _ = String.foldli (fn (c, i) => fn _ => (print (Int.toString(i) ^ " " ^ Int.toString(Char.ord c) ^ "\n"))) 0 str