如果将控制结构作为表达式(以一种很好的方式),如何制作一个if then else

时间:2013-05-24 14:03:46

标签: haskell

我想知道正确而优雅的方式来做这样的事情

function candy = case (color candy) of
    Blue -> if (isTasty candy) then eat candy
            else if (isSmelly candy) then dump candy
            else leave candy

我试过

function candy = case (color candy) of
    Blue -> dealWith candy
        where dealWith c
                | isTasty c = eat candy
                | isSmelly c = dump candy
                | otherwise = leave candy

任何人都知道如何改进这个?

更多

我知道我可以使用这个

function candy = case (color candy) of
    Blue -> case () of
                _ | isTasty candy -> eat candy
                  | isSmelly candy -> dump candy
                  | otherwise -> leave candy

但使用case而不匹配任何东西似乎都不是正确的方法。

3 个答案:

答案 0 :(得分:16)

您可以直接在外部case表达式中使用警卫。

fun candy = case color candy of
    Blue | isTasty candy  -> eat candy
         | isSmelly candy -> dump candy
         | otherwise      -> leave candy

答案 1 :(得分:11)

您可以在GHC 7.6中使用Multi-way if-expressions

fun candy = case color candy of
    Blue -> if | isTasty candy -> eat candy
               | isSmelly candy -> dump candy
               | otherwise -> leave candy

答案 2 :(得分:3)

您可以使用元组创建类似于表的结构。我知道这样做:

function candy = case (color candy, isTasty candy, isSmelly candy) of
  (Blue, True, _   ) -> eat candy
  (Blue,    _, True) -> dump candy
   _                 -> leave candy