Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

absolute values in Haskell

Tags:

haskell

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?

like image 567
user147056 Avatar asked Jul 30 '09 18:07

user147056


People also ask

How do you do absolute value?

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.”

What is absolute value function example?

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.

How do absolute value functions work?

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.


1 Answers

Both of them seem to work just fine:

Main> myabs 1
1
Main> myabs (-1)
1
Main> abs 1
1
Main> abs (-1)
1
like image 170
andri Avatar answered Sep 18 '22 13:09

andri