我想知道做这种事的正确和优雅的方式
function candy = case (color candy) of
Blue -> if (isTasty candy) then eat candy
else if (isSmelly candy) then dump candy
else leave candy
Run Code Online (Sandbox Code Playgroud)
我试过了
function candy = case (color candy) of
Blue -> dealWith candy
where dealWith c
| isTasty c = eat candy
| isSmelly c = dump candy
| otherwise = leave candy
Run Code Online (Sandbox Code Playgroud)
谁知道如何改进这个?
更多
我知道我可以用它
function candy = case (color candy) of
Blue -> case () of
_ | isTasty candy -> eat candy
| isSmelly candy -> dump candy
| otherwise -> leave candy
Run Code Online (Sandbox Code Playgroud)
但是使用一段case时间不匹配任何东西似乎都不是正确的方法.
ham*_*mar 16
您可以直接在外部case表达式中使用警卫.
fun candy = case color candy of
Blue | isTasty candy -> eat candy
| isSmelly candy -> dump candy
| otherwise -> leave candy
Run Code Online (Sandbox Code Playgroud)
Fed*_*lev 11
您可以在GHC 7.6中使用多向if表达式:
fun candy = case color candy of
Blue -> if | isTasty candy -> eat candy
| isSmelly candy -> dump candy
| otherwise -> leave candy
Run Code Online (Sandbox Code Playgroud)