Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- fun curry(f: ('a * 'b) -> 'c) = (fn a => (fn b => f(a, b)));
- fun uncurry(f: ('a -> 'b -> 'c)) = (fn (a, b) => f(a)(b));
- fun f(x, y) = x + y;
- uncurry(curry(f));
- fun g(x) = (fn y => x + y);
- curry(uncurry(g));
- (* Lazy evaluation sequences (infinite lists) *)
- datatype 'a Seq = Cons of 'a * (unit -> 'a Seq);
- fun head (Cons (x, _)) = x;
- fun tail (Cons (_, xs)) = xs();
- (* Get the n'th value in a sequence *)
- fun get(n, s) = if n=0 then head(s) else get(n-1, tail(s));
- (* Sequence of infinite 1's *)
- val ones = let fun f() = Cons(1, f) in f() end;
- (* Sequence of all natural numbers *)
- val natseq = let fun f(n)() = Cons(n, f(n+1)) in f(0)() end;
- (* Merge 2 sequences *)
- fun merge (a : 'a Seq, b : 'a Seq) = Cons (head(a), fn() => merge(b, tail(a)));
- fun make_ints(f) =
- let
- fun make_pos(n) = Cons((n, f(n)), fn() => make_pos(n+1))
- fun make_neg(n) = Cons((n, f(n)), fn() => make_neg(n-1))
- in
- merge (make_pos(0), make_neg(~1))
- end;
- val double = make_ints(fn x => x * 2);
- val plusTen = make_ints(fn x => x + 10);
- get(0, double);
- get(1, double);
- get(2, double);
- get(3, double);
- get(4, double);
- (* Apply a value to a "function" (i.e. to a sequence of input/output pairs) *)
- fun apply (Cons((x1 : int, fx1 : int), xs), x2 : int) =
- if (x1=x2) then fx1
- else apply(xs(), x2);
- (* Function composition -- f(g(x)) *)
- fun compose(f as Cons((x1 : int, y1 : int), xs1), g as Cons((x2 : int, y2 : int), xs2))
- = Cons ((x2, apply(f, y2)), fn() => compose(f, xs2()));
- val doublePlusTen = compose(plusTen, double);
- apply(doublePlusTen, 25);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement