putStrLn function does not accept [Char] parameter

时间:2015-07-28 22:14:47

标签: haskell

Below code :

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 type ‘IO ()’
    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> 

I do not understand error :

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

As putStrLn accepts a [Char] type as first parameter (I assume its implicitly converted to String ?). But this does not type check if "test" ++ "test" is passed as parameter, even though "test" ++ "test" is of type [Char] also ?

1 个答案:

答案 0 :(得分:11)

Your code doesn't pass "test" ++ "test" as a parameter. Function application binds tighter than any infix operator. Your code is parsed as

(putStrLn "test") ++ "test"

The error you get refers to the fact that putStrLn does not return a string.

To solve this, write

putStrLn ("test" ++ "test")

Note: String is defined as type String = [Char], i.e. it's just a different name for the same type.