Issue
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?
Solution
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.
Answered By - Chris Answer Checked By - Pedro (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.