简体   繁体   中英

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?

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

When you type

absF -1.0;;

OCaml interprets it as

(absF) - (1.0);;

ie as a subtraction. Instead, do

absF (-1.0);;

if you have int value can use

# abs(-1)
- : int = 1

else if you have a float

# abs_float(-1.0)
- : float = 1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM