views:

306

answers:

2

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?

+3  A: 

When you type

absF -.1.0;;

OCaml interprets it as

(absF) -. (1.0);;

i.e. as a subtraction. Instead, do

absF (-.1.0);;
Mark Probst
+4  A: 

can I suggest 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
nlucaroni