Advertisement
uyuyuy99

CS 425 - Ass 4

Jun 9th, 2025
380
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. fun curry(f: ('a * 'b) -> 'c) = (fn a => (fn b => f(a, b)));
  2. fun uncurry(f: ('a -> 'b -> 'c)) = (fn (a, b) => f(a)(b));
  3.  
  4. fun f(x, y) = x + y;
  5. uncurry(curry(f));
  6.  
  7. fun g(x) = (fn y => x + y);
  8. curry(uncurry(g));
  9.  
  10.  
  11. (* Lazy evaluation sequences (infinite lists) *)
  12. datatype 'a Seq = Cons of 'a * (unit -> 'a Seq);
  13. fun head (Cons (x, _)) = x;
  14. fun tail (Cons (_, xs)) = xs();
  15.  
  16. (* Get the n'th value in a sequence *)
  17. fun get(n, s) = if n=0 then head(s) else get(n-1, tail(s));
  18.  
  19. (* Sequence of infinite 1's *)
  20. val ones = let fun f() = Cons(1, f) in f() end;
  21.  
  22. (* Sequence of all natural numbers *)
  23. val natseq = let fun f(n)() = Cons(n, f(n+1)) in f(0)() end;
  24.  
  25. (* Merge 2 sequences *)
  26. fun merge (a : 'a Seq, b : 'a Seq) = Cons (head(a), fn() => merge(b, tail(a)));
  27.  
  28. fun make_ints(f) =
  29. let
  30.   fun make_pos(n) = Cons((n, f(n)), fn() => make_pos(n+1))
  31.   fun make_neg(n) = Cons((n, f(n)), fn() => make_neg(n-1))
  32. in
  33.   merge (make_pos(0), make_neg(~1))
  34. end;
  35.  
  36. val double = make_ints(fn x => x * 2);
  37. val plusTen = make_ints(fn x => x + 10);
  38. get(0, double);
  39. get(1, double);
  40. get(2, double);
  41. get(3, double);
  42. get(4, double);
  43.  
  44. (* Apply a value to a "function" (i.e. to a sequence of input/output pairs) *)
  45. fun apply (Cons((x1 : int, fx1 : int), xs), x2 : int) =
  46.   if (x1=x2) then fx1
  47.   else apply(xs(), x2);
  48.  
  49. (* Function composition -- f(g(x)) *)
  50. fun compose(f as Cons((x1 : int, y1 : int), xs1), g as Cons((x2 : int, y2 : int), xs2))
  51.     = Cons ((x2, apply(f, y2)), fn() => compose(f, xs2()));
  52. val doublePlusTen = compose(plusTen, double);
  53.  
  54. apply(doublePlusTen, 25);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement