Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 254
Sam Kellett Avatar asked Mar 22 '14 09:03

Sam Kellett


1 Answers

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
like image 196
Daddlo Avatar answered Sep 18 '22 05:09

Daddlo