Home > Mobile >  How to return a float in OCaml?
How to return a float in OCaml?

Time:06-04

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?

CodePudding user response:

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.
  • Related