Haskell Absolute Values

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 

Both of them work for positive integers, but not for negative integers. Any idea why?

+6
haskell
source share
3 answers

Both of them seem very good:

  Main> myabs 1
 one
 Main> myabs (-1)
 one
 Main> abs 1
 one
 Main> abs (-1)
 one
+10
source share

Ahhh! I did not know that you need to include brackets in ...

 myabs (-1) 

someone skips a dunces hat. dohhh

+5
source share

That's right, you usually need to enclose negative values ​​in parentheses to fix the operator precedence problem. For more information, see Real World Haskell, Chapter 1 .

+4
source share

All Articles