一个函数是否可以返回多个值——例如,一个字符串和一个 bool 值?
如果是,那么我有一个名为 concat
的函数,它返回一个 Bool
和一个 String
,但我不知道如何调用该函数,以便我可以存储结果。
示例尝试:
concat::(String->Int)->(IO Bool->IO String)
concat line i=do
return True line
你能帮我写一下函数签名以及如何调用这些函数吗?
最佳答案
当返回多个值时,您必须返回代数数据类型。关于这一点可以说很多,我会给你一些建议。
如果您的
Bool
和String
在某种程度上更相关,并且它们经常一起出现在您的代码中,请定义一个新的代数数据类型:data Question = Question Bool String
您还可以使用访问器函数来定义它,该函数也记录数据:
data Question = Question{ answered :: Bool , text :: String }
你可以定义一个函数e。 G。用于初始化问题:
question :: String -> Question question str = Question False (str ++ "?")
或(为了改进文档):
question :: String -> Question question str = Question{ answered = False , text = str ++ "?"}
然后您可以使用数据构造函数处理您的数据:
answer :: String -> Question -> Question answer answ (Question False str) = Question True (str ++ " " ++ answ ++ ".") answer _ old = old
或使用访问器函数(两种方法的多种组合都是可能的):
answer :: String -> Question -> Question answer answ qstn | answered qstn = qstn | otherwise = qstn{ answered = True , text = text qstn ++ " " ++ answ ++ "."}
调用函数的示例:
answer "Yes it is" (question "Is this answer already too long")
如果您不想定义新的数据类型,请使用预定义的元组。标准库中定义了许多函数,这使您更轻松地处理元组。但是,不要到处使用元组 - 更大的代码会变得一团糟(缺乏文档 - 不清楚元组代表什么数据),由于多态性,类型错误不会那么容易追踪。
元组的便捷使用示例:
squareAndCube :: Int -> (Int, Int) squareAndCube x = (square, square*x) where square = x*x sumOfSquareAndCube :: Int -> Int sumOfSquareAndCube x = square + cube where (square, cube) = squareAndCube x
关于这个简单的问题已经说得太多了,但由于我提到标准库支持是元组的主要优点,所以我将给出最后一个使用 Prelude 中的
uncurry
函数的示例:sumOfSquareAndCube :: Int -> Int sumOfSquareAndCube x = uncurry (+) (squareAndCube x)
关于haskell - 我如何从 haskell 中的函数返回多个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25043077/