简体   繁体   中英

How to return a float in OCaml?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM