Sometimes I write code like this
solveLogic :: Int -> Int -> Int solveLogic a b = let x = 1 brainiac | a >= x = 1 | a == b = 333 | otherwise = 5 in brainiac
And every time I have urge to write this things without unneeded "brainiac" function, like this:
solveLogic :: Int -> Int -> Int solveLogic a b = let x = 1 in | a >= x = 1 | a == b = 333 | otherwise = 5
Which code is much more "Haskellish". Is there any way of doing this?
Haskell guards are used to test the properties of an expression; it might look like an if-else statement from a beginner's view, but they function very differently. Haskell guards can be simpler and easier to read than pattern matching .
It's not equivalent to _ , it's equivalent to any other identifier. That is if an identifier is used as a pattern in Haskell, the pattern always matches and the matched value is bound to that identifier (unlike _ where it also always matches, but the matched value is discarded).
Yes, using a where
clause:
solveLogic a b | a >= x = 1 | a == b = 333 | otherwise = 5 where x = 1
When I want guards as an expression I use this somewhat ugly hack
case () of _ | a >= x -> 1 | a == b -> 333 | otherwise -> 5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With