gpt4 book ai didi

Haskell:单个函数中的多个 Case 语句

转载 作者:行者123 更新时间:2023-12-02 09:41:31 25 4
gpt4 key购买 nike

我想在 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."

请注意,如果我的功能很简单:

tester x y =  
case (x < 0) of
True -> "less than zero."
False -> "greater than or equal to zero."

...然后它就会编译。

最佳答案

一般the body of a function has to be a single expression (通常由较小的表达式组成)。例如,以下内容是不允许的:

f x y =
"foo"
"bar"

这相当于您的第一个示例 - 我们只是用一种表达式(字符串文字)替换了另一种表达式(您的 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."

或者甚至:

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."

这些之所以有效,是因为函数体是单个表达式(尽管两者都不是真正惯用的 Haskell)。

关于Haskell:单个函数中的多个 Case 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4242002/

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