简单的OCaml练习 [英] Simple OCaml exercise

查看:67
本文介绍了简单的OCaml练习的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过Jason Hickey笔记来自学OCaml,以下练习使我感到困惑. 问题:编写一个给定两个整数边界 m,n 的函数 sum ,而函数 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.

推荐答案

您需要一些括号.

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

(尽管出于可读性考虑,我通常会在最后一行加上(f m) + (sum n (m+1) f).) 没有括号的情况是将其视为(f m) + (sum n m) + (1 f),这会产生sum n m没有类型int的错误,因为它是具有更复杂类型的部分函数应用程序.

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

作为一般规则,当将表达式作为参数传递给函数时,始终需要将其括在括号中.在相关说明中,如果您确实想将plus函数作为参数传递,则可以将其放在括号中(例如:sum m n (+)(尽管在这种情况下不会键入check,因为+期望两个数字) ).

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

这篇关于简单的OCaml练习的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆