Skip to content

Instantly share code, notes, and snippets.

@toretto460
Last active December 27, 2015 04:39
Show Gist options
  • Save toretto460/7268617 to your computer and use it in GitHub Desktop.
Save toretto460/7268617 to your computer and use it in GitHub Desktop.
Standard ML Examples
(* Type checker *)
fun fReal (x) = x + 0.0;
fun fInteger (x) = x + 0;
(*
if true then fReal(3.0) else fInteger(3);
Error: types of if branches do not agree !!
*)
(* call by value *)
fun myif a b c = if a then b else c;
fun fact n = myif (n=0) 1 (n* fact(n-1));
(* infinite execution
fact 3
myif false 1 (3 * fact 2)
myif false 1 (2 * fact 1)
myif false 1 (1 * fact 0)
myif true 1 (0 * fact -1)
the myif execution cause fact -1 evaluation and the infinite execution
*)
(* scope *)
val x = 2;
val x = 4 and y = x + 1;
(* at the second line "x" has the value 2 *)
(* pattern matching *)
val p = (true, 10);
val (left , right) = p;
(*the pattern order is important
fun wrong_fact n = n*wrong_fact(n-1)
| wrong_fact 0 = 1;
*)
(* wrong_fact 8; Error because redundant match 0*)
fun fact 0 = 1
| fact n = n * fact(n-1);
fact 3;
(* records and record wildcards *)
val r = {name = "ric", age = 50};
val {name = n, ...} = r;
(* the second expression the "ric" value to n *)
(* polymorphism: monotypes & polytypes *)
fun incFirst (x, y) = (x+1, y);
incFirst(90, 30);
(* the identity function *)
val id = fn x => x;
id "STR";
id 30;
id 3.9;
(* equals *)
fun equals a b = (a = b);
(* equals id 4; it fails at runtime because operator and operand don't agree *)
(* a function that return the first arg *)
fun first x y = x;
first (fn x:int => x) 10;
(* is the same of first *)
val ufst = fn x => fn y => x;
ufst (fn x:int => x) 10;
(* higher order functions *)
fun compose f g x = f(g x);
fun negative x = ~x;
compose negative negative ~10;
compose negative negative 10;
(* sum *)
fun sum f 0 = 0
| sum f n = (f n) + sum f (n-1);
sum id 8;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment