PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, July 19, 2022

[FIXED] How to return a float in OCaml?

 July 19, 2022     function, integer, list, ocaml     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing