I am trying to write a function that returns the absolute value of an integer...
abs :: Int -> Int
abs n | n >= 0 = n
| otherwise = -n
myabs :: Int -> Int
myabs n = if n >= 0 then n else -n
They both work for positive integers but not negative integers. Any idea why?
The most common way to represent the absolute value of a number or expression is to surround it with the absolute value symbol: two vertical straight lines. |6| = 6 means “the absolute value of 6 is 6.” |–6| = 6 means “the absolute value of –6 is 6.” |–2 – x| means “the absolute value of the expression –2 minus x.”
The absolute value (or modulus) | x | of a real number x is the non-negative value of x without regard to its sign. For example, the absolute value of 5 is 5, and the absolute value of −5 is also 5. The absolute value of a number may be thought of as its distance from zero along real number line.
Recall that in its basic form f(x)=|x|, the absolute value function, is one of our toolkit functions. The absolute value function is commonly thought of as providing the distance the number is from zero on a number line. Algebraically, for whatever the input value is, the output is the value without regard to sign.
Both of them seem to work just fine:
Main> myabs 1 1 Main> myabs (-1) 1 Main> abs 1 1 Main> abs (-1) 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With