Sam Kellett
Sam Kellett

Reputation: 1347

Can I overload a Haskell function based on a Bool function call?

I'm not sure how to explain this very well so I'll just provide an example:

-- Create a list of ints if the string contains no numbers
row :: String -> [Maybe Int]
row (isAlpha row) = [ Just $ ord c | c <- row ]
row _ = [Nothing]

When I try to load a module with this in it in GHCi I get:

Parse error in pattern: isAlpha

Is there a way to do this? Or do I have to do it all in an if..else?

Ninja Edit: This isn't a real example, obviously. I tried to extrapolate the behaviour I was after with a simple example but in hindsight this obviously makes no sense as isAlpha would return a Bool, not a String so it would be the wrong parameter and isAlpha works on Char not String's anyway. But I was just trying to portray the concept I was looking for, so I hope that's come through.

Upvotes: 5

Views: 145

Answers (1)

Daddlo
Daddlo

Reputation: 96

you are using isAlpha in a place where pattern matching (and pattern matching only) happens. Use guards instead:

 row a | isAlpha a = someFunction
       | otherwise = someOtherFunction

Upvotes: 8

Related Questions