我想知道正确而优雅的方式来做这样的事情
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
而不匹配任何东西似乎都不是正确的方法。
答案 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