SML 和教堂数字
我有一个作业,需要使用以下数据类型在 SML 中实现教堂数字: datatype 'a Church = C of ('a -'a) * 'a -> 'a
我必须编写函数 create :int -> '一个教堂和一个功能churchToint 到目前为止,我有以下代码:
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 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你是对的,你已经很接近了。 ChurchToInt 函数中只有两个小错误:
您没有解压教堂数字。即,您将参数
cn
视为一个函数,但churchToInt
应该接受一个C
包含 一个函数,而不是一个函数本身。因此,将其更改为fun ChurchToInt (C cn) =
,通过模式匹配来解压该函数。您使用柯里化风格将两个参数应用于函数,但
C
已定义为包含一个采用元组的函数。因此,不要写cn (fn x => x+1) 0
,而是写cn ((fn x => x+1), 0)
。通过这两个更改,您的代码可以正常工作。
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
cn
like a function, butchurchToInt
should accept aC
containing 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
C
has 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.