I was wondering the correct and elegant way to do such a thing
function candy = case (color candy) of
Blue -> if (isTasty candy) then eat candy
else if (isSmelly candy) then dump candy
else leave candy
I tried
function candy = case (color candy) of
Blue -> dealWith candy
where dealWith c
| isTasty c = eat candy
| isSmelly c = dump candy
| otherwise = leave candy
Anyone knows how to improve on this?
MORE
I know I can use this
function candy = case (color candy) of
Blue -> case () of
_ | isTasty candy -> eat candy
| isSmelly candy -> dump candy
| otherwise -> leave candy
But using a case
while not matching anything just doesn't seem to be the right way.
Use the If… Then… Else statement to define two blocks of statements. One of the statements runs when the specified condition is True, and the other one runs when the condition is False. When you want to define more than two blocks of statements, use the ElseIf Statement.
IF-ELES: if the condition is true, then the block of code inside the IF statement is executed; otherwise, the block of code inside the ELSE is executed. IF-ELSE-IF: if the condition is true, then the block of code inside the IF statement is executed. After that, the ELSE-IF block is checked.
The if / then statement is a conditional statement that executes its sub-statement, which follows the then keyword, only if the provided condition evaluates to true: if x < 10 then x := x+1; In the above example, the condition is x < 10 , and the statement to execute is x := x+1 .
Syntax. Use the IF function, one of the logical functions, to return one value if a condition is true and another value if it's false. For example: =IF(A2>B2,"Over Budget","OK")
You can use guards directly in your outer case
expression.
fun candy = case color candy of
Blue | isTasty candy -> eat candy
| isSmelly candy -> dump candy
| otherwise -> leave candy
You can use Multi-way if-expressions in GHC 7.6:
fun candy = case color candy of
Blue -> if | isTasty candy -> eat candy
| isSmelly candy -> dump candy
| otherwise -> leave candy
You can make a table-like structure using tuples. I've been known to do this:
function candy = case (color candy, isTasty candy, isSmelly candy) of
(Blue, True, _ ) -> eat candy
(Blue, _, True) -> dump candy
_ -> leave candy
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With