Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using guards in let .. in expressions

Tags:

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?

like image 787
Rijk Avatar asked Apr 29 '12 07:04

Rijk


People also ask

When should I use guards in Haskell?

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 .

What is otherwise in Haskell?

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).


2 Answers

Yes, using a where clause:

solveLogic a b         | a >= x     = 1         | a == b     = 333         | otherwise  = 5     where       x = 1 
like image 115
huon Avatar answered Oct 02 '22 19:10

huon


When I want guards as an expression I use this somewhat ugly hack

case () of _ | a >= x     -> 1   | a == b     -> 333   | otherwise  -> 5 
like image 30
augustss Avatar answered Oct 02 '22 18:10

augustss