23

有时我会写这样的代码

solveLogic :: Int -> Int -> Int
solveLogic a b =
    let 
        x = 1
        brainiac
            | a >= x     = 1
            | a == b     = 333
            | otherwise  = 5
    in
        brainiac

每次我都想在没有不需要的“brainiac”功能的情况下写这些东西,就像这样:

solveLogic :: Int -> Int -> Int
solveLogic a b =
    let 
        x = 1
    in
        | a >= x     = 1
        | a == b     = 333
        | otherwise  = 5

哪个代码更“Haskellish”。有没有办法做到这一点?

4

2 回答 2

53

是的,使用一个where子句:

solveLogic a b
        | a >= x     = 1
        | a == b     = 333
        | otherwise  = 5
    where
      x = 1
于 2012-04-29T07:06:02.347 回答
16

当我想要守卫作为一种表达方式时,我会使用这个有点丑陋的技巧

case () of
_ | a >= x     -> 1
  | a == b     -> 333
  | otherwise  -> 5
于 2012-04-29T11:04:55.853 回答