如何在OCAML中返回浮子?

发布于 2025-02-04 06:53:49 字数 340 浏览 1 评论 0原文

我已经在OCAML中编写了此简单功能以计算列表的总和:

let rec sum lst = 
     match lst with
     | [] -> 0.0
     | h :: t -> h + sum t

但是,当我调用它时,我会收到错误:

Error: This expression has type float
   but an expression was expected of type int

如何重写此功能,以便它能够总和一个floats的列表并返回零作为float( 0.0)如果列表为空?

I have written this simple function in OCaml to calculate the sum of a List:

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?

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

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

发布评论

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

评论(1

软糖 2025-02-11 06:53:49

在OCAML Integer数学中,使用+-*/。 - 。,*。

是用+。

let rec sum lst = 
  match lst with
  | [] -> 0.0
  | h :: t -> h +. sum t

浮点数学 您可以写以下内容。不需要浮动点文字上的尾随0。这具有成为尾声的好处。

let sum = List.fold_left (+.) 0.

In OCaml integer math is done with +, -, *, and /. 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. This has the benefit of being tail-recursive.

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