F# 中的递归加法使用
我正在尝试在 F#
m + 0 := m
m + (n + 1) := (m + n) + 1
中实现以下加法的递归定义我似乎无法获得正确的语法,最接近的我've come is
let rec plus x y =
match y with
| 0 -> x;
| succ(y) -> succ( plus(x y) );
其中 succ n = n + 1。它会在 succ 的模式匹配上引发错误。
I'm trying to implement the following recursive definition for addition in F#
m + 0 := m
m + (n + 1) := (m + n) + 1
I can't seem to get the syntax correct, The closest I've come is
let rec plus x y =
match y with
| 0 -> x;
| succ(y) -> succ( plus(x y) );
Where succ n = n + 1. It throws an error on pattern matching for succ.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我不确定
succ
在您的示例中意味着什么,但它不是标准 F# 库中定义的模式。仅使用基本功能,您需要使用匹配任何数字的模式,然后减一(并在主体中加一):在 F# 中(与 Prolog 等不同),您不能在模式中使用自己的函数。但是,您可以定义活动模式来指定如何将输入分解为各种情况。下面的代码接受一个整数,并返回
Zero
(零)或Succ y
值y + 1
:然后您可以编写以下代码 :更接近您的原始版本:
I'm not sure what
succ
means in your example, but it is not a pattern defined in the standard F# library. Using just the basic functionality, you'll need to use a pattern that matches any number and then subtract one (and add one in the body):In F# (unlike e.g. in Prolog), you can't use your own functions inside patterns. However, you can define active patterns that specify how to decompose input into various cases. The following takes an integer and returns either
Zero
(for zero) orSucc y
for valuey + 1
:Then you can write code that is closer to your original version:
正如 Tomas 所说,如果不声明它,就不能像这样使用
succ
。您可以做的是创建一个代表数字的可区分联合:然后在
plus
函数中使用它:或者您可以将其声明为
+
运算符:如果您将
y
保留在我的y1
位置,该代码可以工作,因为第二个y
会隐藏第一个。但我认为这样做会使代码变得混乱。As Tomas said, you can't use
succ
like this without declaring it. What you can do is to create a discriminated union that represents a number:And then use that in the
plus
function:Or you could declare it as the
+
operator:If you kept
y
where I havey1
, the code would work, because the secondy
would hide the first one. But I think doing so makes the code confusing.演示:
DEMO: