Kevvvvyp
Kevvvvyp

Reputation: 1774

Crashing on negative input Haskell

Can anyone explain why this crashes upon negative input?

add :: Integral a => (a -> a) -> a -> a
add f n | n<0  = error "only non-negative integers allowed as input"
    | otherwise     = sum[ f x |x<-[1..n] ]


foo:: Int -> Int
foo x = x

*Main> add foo -5

<interactive>:82:9:
No instance for (Num (Int -> Int))
arising from a use of `-'
Possible fix: add an instance declaration for (Num (Int -> Int))
In the expression: add foo - 5
In an equation for `it': it = add foo - 5

Upvotes: 3

Views: 450

Answers (1)

Zeta
Zeta

Reputation: 105885

You have to write (-5) to make clear you're using the unary -, otherwise haskell is going to read - as the binary operator:

add foo (-5)

Upvotes: 9

Related Questions