tags:

views:

197

answers:

3

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?

+5  A: 

Both of them seem to work just fine:

Main> myabs 1
1
Main> myabs (-1)
1
Main> abs 1
1
Main> abs (-1)
1
andri
+3  A: 

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

myabs (-1)

someone pass the dunces cap. dohhh

This should be a comment (you can do that now). :)
Bill the Lizard
+3  A: 

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

Simon Michael