gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 15:05:52 25 4
gpt4 key购买 nike

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

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

最佳答案

您可以直接在您的外部 case 中使用 guard 表达。

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

关于haskell - 如何将 if then else if 控制结构作为表达式(以一种很好的方式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16736850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com