wel*_*lly 9 haskell case-statement
我想在Haskell函数中包含多个case语句(请参阅下面的假设函数示例).
但是,它不合法Haskell.有什么更好的方法来完成同样的事情?此外,如果case语句没有返回任何内容,只是设置了一些值,为什么在函数中有多个case语句是不合法的?
(我会在第5行得到"输入`case'的解析错误")
tester x y =
case (x < 0) of
True -> "less than zero."
False -> "greater than or equal to zero."
case (y == "foo")
True -> "the name is foo."
False -> "the name is not foo."
Run Code Online (Sandbox Code Playgroud)
请注意,如果我的功能只是:
tester x y =
case (x < 0) of
True -> "less than zero."
False -> "greater than or equal to zero."
Run Code Online (Sandbox Code Playgroud)
...然后它会编译.
Tra*_*own 10
通常,函数体必须是单个表达式(通常由较小的表达式组成).以下是不允许的,例如:
f x y =
"foo"
"bar"
Run Code Online (Sandbox Code Playgroud)
这相当于你的第一个例子 - 我们只是用另一种表达式(字符串文字)替换了另一种表达式(你的case表达式).
在Haskell函数中包含多个case表达式当然是可能的:
tester :: Int -> String -> (String, String)
tester x y = (a, b)
where
a = case (x < 0) of
True -> "less than zero."
False -> "greater than or equal to zero."
b = case (y == "foo") of
True -> "the name is foo."
False -> "the name is not foo."
Run Code Online (Sandbox Code Playgroud)
甚至:
tester :: Int -> String -> IO ()
tester x y = do
putStrLn $ case (x < 0) of
True -> "less than zero."
False -> "greater than or equal to zero."
putStrLn $ case (y == "foo") of
True -> "the name is foo."
False -> "the name is not foo."
Run Code Online (Sandbox Code Playgroud)
这些工作是因为函数的主体是单个表达式(尽管两者都不是真正惯用的Haskell).