I have an assignment where I need to implement church numerals in SML using the datatype: datatype ‘a church = C of (‘a -‘a) * ‘a -> ‘a
I have to write the function create :int -> ‘a church and a function churchToint
So far I have the following code:
datatype 'a church = C of ('a -> 'a) * 'a -> 'a
val ZERO = C(fn (f,x) => x)
fun subCreate 0 (f,x) = x
| subCreate n (f,x) = f (subCreate (n-1) (f,x))
fun create n = C(fn (f,x) => subCreate n (f,x));
fun churchToInt cn = cn (fn x => x + 1) 0;
I know I am pretty close. Can you please assist me in implementing this correctly? Thanks
You are right, you are quite close. There are only two minor mistakes in your churchToInt function:
You’re not unpacking the church numeral. I.e. you treat your argument
cnlike a function, butchurchToIntshould accept aCcontaining a function, not a function itself. So change it tofun churchToInt (C cn) =, to unpack the function via pattern matching.You’re applying two arguments to the function using curry style, but
Chas been defined to contain a function taking a tuple. So instead ofcn (fn x => x+1) 0, writecn ((fn x => x+1), 0).With these two changes your code works fine.