Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Absolute value for floats in core OCaml

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?

like image 526
Mat Kelly Avatar asked Mar 20 '09 17:03

Mat Kelly


3 Answers

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
like image 57
nlucaroni Avatar answered Sep 18 '22 02:09

nlucaroni


When you type

absF -1.0;;

OCaml interprets it as

(absF) - (1.0);;

i.e. as a subtraction. Instead, do

absF (-1.0);;
like image 25
Mark Probst Avatar answered Sep 18 '22 02:09

Mark Probst


if you have int value can use

# abs(-1)
- : int = 1

else if you have a float

# abs_float(-1.0)
- : float = 1.
like image 27
daniele3004 Avatar answered Sep 19 '22 02:09

daniele3004