Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading