【发布时间】:2021-06-24 02:58:48
【问题描述】:
所以我有这个函数应该返回一个字符串(或 [Char])。这是它的一个非常简单的版本:
test :: Int -> Int -> [Char]
test n1 n2 = do
if n1 >= n2 then return "return 1"
else do
(...)
return "return 2"
现在据我了解,“return 1”和“return 2”是字符串。它们应该具有 [Char] 类型。但是由于某种原因,当我编译它时,出现以下错误:
Cards.hs:284:22: error:
• Couldn't match type ‘[Char]’ with ‘Char’
Expected type: [Char]
Actual type: [[Char]]
• In the expression: return "return 1"
In a stmt of a 'do' block:
if n1 >= n2 then return "return 1" else do return "return 2"
In the expression:
do if n1 >= n2 then return "return 1" else do return "return 2"
|
284 | if n1 >= n2 then return "return 1"
当程序将这些字符串识别为 [[Char]] 时,谁能告诉我?因为我也尝试过在返回之前连接返回值,当我这样做时,它识别为类型 [Char]。
【问题讨论】:
-
简短回答:除非你知道你需要它们,否则不要使用
do和return -
这是由于
return,这意味着您将项目包装在一个单子上下文中,这里该上下文是一个列表,这意味着您创建一个单例列表。 -
@WillemVanOnsem 请问我该如何解决这个问题?
-
基本上
if n1 > n2 then "return 1" else "return 2"
标签: haskell types functional-programming