SML 和教堂数字

发布于 2024-09-24 20:48:48 字数 478 浏览 0 评论 0原文

我有一个作业,需要使用以下数据类型在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

吹泡泡o 2024-10-01 20:48:48

你是对的,你已经很接近了。 ChurchToInt 函数中只有两个小错误:

  1. 您没有解压教堂数字。即,您将参数 cn 视为一个函数,但 churchToInt 应该接受一个 C 包含 一个函数,而不是一个函数本身。因此,将其更改为 fun ChurchToInt (C cn) =,通过模式匹配来解压该函数。

  2. 您使用柯里化风格将两个参数应用于函数,但 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:

  1. You're not unpacking the church numeral. I.e. you treat your argument cn like a function, but churchToInt should accept a C containing a function, not a function itself. So change it to fun churchToInt (C cn) =, to unpack the function via pattern matching.

  2. 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 of cn (fn x => x+1) 0, write cn ((fn x => x+1), 0).

With these two changes your code works fine.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文