Advertisement
Guest User

Untitled

a guest
Jul 19th, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 1.41 KB | None | 0 0
  1. (*
  2.   One way of representing nonnegative integers is called “Peano numerals” and we define
  3.   the type of a peano numeral as follows:
  4.   datatype 'a peano = C of ('a -> 'a) * 'a -> 'a
  5.   We can think of a peano numeral as a function that is applied to some base number n
  6.   times. For example:
  7.    0 is represented as ZERO = C(fn (f,x) => x)
  8.    1 is represented as ONE = C(fn (f,x) => f(x))
  9.    2 is represented as TWO = C(fn (f,x) => f(f(x)))
  10.    ...
  11. *)
  12.  
  13. datatype 'a peano = C of ('a -> 'a) * 'a -> 'a;
  14.  
  15. (* 2.1
  16.  
  17.   Write a function create:int -> 'a peano which when given an integer it will
  18.   generate a peano numeral. Ensure that the resulting peano numeral you return
  19.   does not contain any calls to the function create.
  20. *)
  21.  
  22. (* create:int -> 'a peano *)
  23.  
  24. fun create(n) =
  25.     let
  26.     fun create'(0) = (fn (f,x) => x)
  27.           | create'(n) = (fn (f,x) => f(create'(n-1) (f, x)))
  28.     in
  29.     C(create'(n))
  30.     end
  31.  
  32. (* 2.2
  33.  
  34.   Write a function peanoToInt which accepts a peano numeral as input and converts
  35.   it into an integer.
  36. *)
  37.  
  38. (* peanoToInt: [__] peano -> int *)
  39. (* note the [__] will not necessarily be 'a *)
  40.  
  41. (* Also note, writing code of the form
  42.  
  43.   val pn = create(42);
  44.   peanoToInt( pn );
  45.  
  46. may not work.
  47. You should, however, be able to write
  48.  
  49.   peanoToInt(create(42));
  50.  
  51. or
  52.   let
  53.       val pn = create(42)
  54.   in
  55.       peanoToInt(pn)
  56.   end
  57. *)
  58.  
  59. fun peanoToInt(p) = p (fn x => x+1, 0)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement