Haskell 如何将if-then-else-if控件结构作为表达式(以一种很好的方式)

Haskell 如何将if-then-else-if控件结构作为表达式(以一种很好的方式),haskell,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 ->

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

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

但是,在不匹配任何内容的情况下使用
大小写似乎不是正确的方法。

您可以使用元组创建类似于表的结构。大家都知道我会这么做:

function candy = case (color candy, isTasty candy, isSmelly candy) of
  (Blue, True, _   ) -> eat candy
  (Blue,    _, True) -> dump candy
   _                 -> leave candy
您可以在GHC 7.6中使用:

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

您可以直接在外部
外壳中使用防护装置

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

这是一个有趣的结构;虽然在这种情况下有点多余。还有,如果你有任意的布尔函数,你就不能用它来计算“任意的布尔函数”是什么意思?嗯,也许我错了,它可以处理大多数情况。我想消极的一面是你需要写一个长的列表元组如果你有很多谓词要计算。在这种情况下,你需要创建一个数据类型来表示可能性,并使用它来简化结构。最后我采用了你的方法。然而,我想知道为什么在where中有一个函数定义是不正确的work@yulan6248当前位置这里很好用。您可以在
案例
的每个备选方案上使用
where
子句,它们在警卫之间共享,就像在函数上一样。请参阅了解详细信息。Thx,我的错,这是一个缩进问题。我是哈斯凯尔的超级新手,请容忍我问一些愚蠢的问题。这个结构叫什么?我们初学者了解到案例中的子句如下所示:pattern1->result1@7stud当前位置我不知道是否有一个公认的名称。您可能会将它们称为“保护的案例替代方案”或“案例表达式中的保护”。你可以看到。