7

我想知道做这件事的正确和优雅的方式

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时间不匹配任何东西似乎不是正确的方法。

4

3 回答 3

16

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

fun candy = case color candy of
    Blue | isTasty candy  -> eat candy
         | isSmelly candy -> dump candy
         | otherwise      -> leave candy
于 2013-05-24T14:11:01.440 回答
11

您可以在 GHC 7.6中使用多路 if 表达式:

fun candy = case color candy of
    Blue -> if | isTasty candy -> eat candy
               | isSmelly candy -> dump candy
               | otherwise -> leave candy
于 2013-05-24T14:09:56.117 回答
3

您可以使用元组创建类似表的结构。众所周知,我会这样做:

function candy = case (color candy, isTasty candy, isSmelly candy) of
  (Blue, True, _   ) -> eat candy
  (Blue,    _, True) -> dump candy
   _                 -> leave candy
于 2013-05-24T14:09:14.680 回答