Question

I am in need of an absolute value function for floats in OCaml and the core language doesn't seem to possess one, so I wrote the following:

let absF (f:float) = if f > 0.0 then f else (f *. -1.0);;

which seems to work for positives but not for negatives, citing:

This expression has type float -> float but is here used with type int

What is the error in my logic?

Was it helpful?

Solution

When you type

absF -1.0;;

OCaml interprets it as

(absF) - (1.0);;

i.e. as a subtraction. Instead, do

absF (-1.0);;

OTHER TIPS

The core language does have one, abs_float.

Also, you can use ~-. to denote unary negation, and this applies to integers as well with the ~- operator. You can define such an operator (even though it already exists) like this:

let (~-) a : int = 0 - a
let (~-.) a : float = 0.0 -. a

if you have int value can use

# abs(-1)
- : int = 1

else if you have a float

# abs_float(-1.0)
- : float = 1.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top