[英]How to return a float in OCaml?
I have written this simple function in OCaml to calculate the sum of a List:我在 OCaml 中编写了这个简单的函数来计算列表的总和:
let rec sum lst =
match lst with
| [] -> 0.0
| h :: t -> h + sum t
However I receive an Error when I call it:但是,当我调用它时收到错误消息:
Error: This expression has type float
but an expression was expected of type int
How can I rewrite this function so it is able to sum a List of floats and return a zero as a float (0.0) if the List is empty?如何重写此函数,以便它能够对浮点列表求和并在列表为空时返回零作为浮点 (0.0)?
In OCaml integer math is done with +
, -
, *
, and /
.在 OCaml 中,整数数学是用
+
、 -
、 *
和/
完成的。 Floating point math is done with +.
浮点数学是用
+.
, -.
,
-.
, *.
,
*.
, and /.
, 和
/.
You want:你要:
let rec sum lst =
match lst with
| [] -> 0.0
| h :: t -> h +. sum t
Although you could just write the following.尽管您可以只写以下内容。 The trailing
0
on floating point literals is not required.浮点文字的尾随
0
不是必需的。 This has the benefit of being tail-recursive.这具有尾递归的好处。
let sum = List.fold_left (+.) 0.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.