putStrLn函数不接受[Char]参数。

4
以下代码:

Prelude> :t putStrLn
putStrLn :: String -> IO ()
Prelude> putStrLn "test"
test
it :: ()
Prelude> putStrLn "test" ++ "test"

<interactive>:25:1:
    Couldn't match expected type ‘[Char]’ with actual typeIO ()’
    In the first argument of ‘(++)’, namely ‘putStrLn "test"In the expression: putStrLn "test" ++ "test"
Prelude> :t "test"
"test" :: [Char]
Prelude> :t "test" ++ "test" 
"test" ++ "test" :: [Char]
Prelude> 

我不理解错误:
" Couldn't match expected type ‘[Char]’ with actual type ‘IO ()’
        In the first argument of ‘(++)’, namely ‘putStrLn "test"’
        In the expression: putStrLn "test" ++ "test""

putStrLn接受[Char]类型作为第一个参数时(我认为它会被隐式转换为String?),但如果将"test" ++ "test"作为参数传递,则无法进行类型检查,即使"test" ++ "test"也是[Char]类型?

5
在 Haskell 中不存在隐式类型转换。 String 只是 [Char] 的类型同义词,也就是完全相同的东西。发生的是多态值(例如数字字面量)的特化,但一旦选择了具体类型,它不会自行更改为其他类型。 - duplode
1个回答

11

您的代码不能将"test" ++ "test"作为参数通过。函数应用比任何中缀运算符都更紧密。您的代码被解析为

(putStrLn "test") ++ "test"

您遇到的错误是因为putStrLn没有返回字符串。

要解决这个问题,请编写:

putStrLn ("test" ++ "test")

注意:String被定义为type String = [Char],也就是说它只是同一类型的不同名称。


耶,很简单的答案,避免谈论 IO 及其诡计。 - luqui

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接