9

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?

mskfisher
  • 3,291
  • 4
  • 35
  • 48
Mat Kelly
  • 2,327
  • 7
  • 29
  • 51

3 Answers3

15

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
nlucaroni
  • 47,556
  • 6
  • 64
  • 86
11

When you type

absF -1.0;;

OCaml interprets it as

(absF) - (1.0);;

i.e. as a subtraction. Instead, do

absF (-1.0);;
newacct
  • 119,665
  • 29
  • 163
  • 224
Mark Probst
  • 7,107
  • 7
  • 40
  • 42
4

if you have int value can use

# abs(-1)
- : int = 1

else if you have a float

# abs_float(-1.0)
- : float = 1.
daniele3004
  • 13,072
  • 12
  • 67
  • 75