Rijk
Rijk

Reputation: 612

Using guards in let .. in expressions

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?

Upvotes: 23

Views: 12188

Answers (2)

augustss
augustss

Reputation: 23014

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

case () of
_ | a >= x     -> 1
  | a == b     -> 333
  | otherwise  -> 5

Upvotes: 16

huon
huon

Reputation: 102066

Yes, using a where clause:

solveLogic a b
        | a >= x     = 1
        | a == b     = 333
        | otherwise  = 5
    where
      x = 1

Upvotes: 54

Related Questions