1
votes

I just started learning Haskell, and i'm on stuck on this error among a bunch of others

i'm trying to print all the characters in the char list recursively with this code

printall :: [Char] -> [Char]
printall "" = ""
printall (i:is) = if is /= "" then print i else printall is

main = printall "hello world"

but i get this error could anyone help me?

intro.hs:14:36: error:
• Couldn't match expected type ‘[Char]’ with actual type
‘IO ()’
• In the expression: print i
  In the expression: if is /= "" then print i else printa
ll is
  In an equation for ‘printall’:
      printall (i : is) = if is /= "" then print i else p
 rintall is

intro.hs:16:1: error:
• Couldn't match expected type ‘IO t0’ with actual type ‘
[Char]’
2
Please justify the type signature you gave to printall, or perhaps just remove it and see what happens.n. 1.8e9-where's-my-share m.
@n.m. i guess the type signature is redundant, the same error persists without itSirTee
Great, now you have this printall "" = "" line, and also printall (i:is) line. The latter has print i in the then branch and printall is in the else branch, The types of the two expressions ought to be the same. Are they?n. 1.8e9-where's-my-share m.
If you want your function to return a string without doing any IO, you use [Char] as the return type. If you want it to do IO and not return a value, use IO () as a return type. If you want to both return a string and do IO then use IO [Char] as a return type. Whatever type you choose, you must be coherent with it in all the branches of your code.chi
No, print t would not return a Char. It's an IO function. You can check its type by entering :t print at ghci prompt.n. 1.8e9-where's-my-share m.

2 Answers

3
votes

As you said in a comment above, each branch of the if clause should have the same type, indeed.

Also, main function must always have IO a type, for some a, which is usually (). This means that the type signature for printall should be:

printall :: [Char] -> IO ()

which is the same as:

printall :: String -> IO ()
0
votes

print type is print :: Show a => a -> IO ()

but your printall type is printall :: [Char] -> [Char], assume it is what you want.

The expression if x then y else z need the same type for y and z