简单的 OCaml 练习

发布于 2024-12-09 20:00:29 字数 269 浏览 0 评论 0原文

我试图通过 Jason Hickey 笔记自学 OCaml,下面的练习让我难住了。 问题:编写一个函数 sum,给定两个整数边界 m,n 和一个函数 f 计算总和。 我正在尝试这个:

     let rec sum m n f=
     if m>n then 0
     else if m=n then f n
     else f m + sum n m+1 f

但它不起作用,产生类型错误。

I'm trying to teach myself OCaml through Jason Hickey notes and the following exercise got me stumped.
Question: Write a function sum that given two integer bounds m,n and a function f computes a summation.
I'm trying this:

     let rec sum m n f=
     if m>n then 0
     else if m=n then f n
     else f m + sum n m+1 f

but it doesn't work, producing a type error.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

凉城 2024-12-16 20:00:29

你需要一些括号。

let rec sum m n f=
     if m>n then 0
     else if m=n then f n
     else f m + sum n (m+1) f

(尽管为了可读性,我通常会将最后一行括起来,如 else (fm) + (sum n (m+1) f)。)
没有括号时发生的情况是,它将其视为 (fm) + (sum nm) + (1 f) ,这会产生 sum n m 没有的错误类型 int,因为它是具有更复杂类型的偏函数应用程序。

作为一般规则,当表达式作为参数传递给函数时,它总是需要加上括号。与此相关的是,如果您实际上想要将 plus 函数作为参数传递,则可以将其放在括号中(例如: sum mn (+) (尽管这不会键入 check in在这种情况下,因为 + 需要两个数字))。

You need some parentheses.

let rec sum m n f=
     if m>n then 0
     else if m=n then f n
     else f m + sum n (m+1) f

(Although for readability, I would usually parenthesize the last line as else (f m) + (sum n (m+1) f). )
What's happening without the parentheses is that it's treating it as (f m) + (sum n m) + (1 f) which is producing the error that sum n m doesn't have type int, as it's a partial function application with a more complex type.

As a general rule, when an expression is being passed as an argument to a function, it always needs to be parenthesized. On a related note, if you ever actually wanted to pass the plus function as an argument, you would put it in parentheses (for example: sum m n (+) (although that wouldn't type check in this case, since + expects two numbers)).

白日梦 2024-12-16 20:00:29

函数应用(函数名称与其参数的绑定)在 OCaml 中具有最高优先级。所以,你需要注意你的括号。我不会给出解决方案,因为自己解决可能会更有趣。

Function application (binding of function names to their arguments) has the highest precedence in OCaml. So, you need to watch your parentheses. I'm not giving the solution because it might be more fun to figure it out yourself.

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