user147056
user147056

Reputation: 397

absolute values in 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?

Upvotes: 8

Views: 18068

Answers (3)

user147056
user147056

Reputation: 397

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

myabs (-1)

someone pass the dunces cap. dohhh

Upvotes: 10

Simon Michael
Simon Michael

Reputation: 2298

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

Upvotes: 6

andri
andri

Reputation: 11292

Both of them seem to work just fine:

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

Upvotes: 13

Related Questions