Simple OCaml exercise

穿精又带淫゛_ 提交于 2019-12-10 17:06:25

问题


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.


回答1:


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)).




回答2:


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.



来源:https://stackoverflow.com/questions/7775075/simple-ocaml-exercise

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!