absolute values in Haskell

Tag: haskell Author: dandan2988409 Date: 2009-07-14

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?

Other Answer1

Both of them seem to work just fine:

Main> myabs 1
1
Main> myabs (-1)
1
Main> abs 1
1
Main> abs (-1)
1

Other Answer2

Right, you usually need to parenthesise negative values to disambiguate operator precedence. For more details, see Real World Haskell chapter 1.

Other Answer3

Ahh! I didn't know you had to include brackets in...

myabs (-1)

someone pass the dunces cap. dohhh

comments:

This should be a comment (you can do that now). :)
^ Self referential :D
Recursive communication. :D