P
P
President422015-05-13 21:07:00
Haskell
President42, 2015-05-13 21:07:00

Why doesn't head work with strings in Haskell?

import Data.List

main :: IO()
main = do
    word <- getLine
    putStrLn(head word)

$ ghc Main.hs
[1 of 1] Compiling Main             ( Main.hs, Main.o )

Main.hs:6:19:
    Couldn't match type `Char' with `[Char]'
    Expected type: [String]
      Actual type: String
    In the first argument of `head', namely `word'
    In the first argument of `putStrLn', namely `(head word)'
    In a stmt of a 'do' block: putStrLn (head word)

Compiler GHC 7.6.3, OS Debian Jessie
PS It says here that the function headmust take an array of elements of any type ( head :: [a] -> a), but a string is considered an array [Char], isn't it?
PPS In REPL (ghci) everything works

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Lolshto, 2015-05-13
@President42

putStrLn can only print strings

Prelude> :t putStrLn
putStrLn :: String -> IO ()

A head wordreturns a character .
You need to convert it to a string, for example
putStrLn . show $ head word

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question