0

I need to get an input until the empty line is entered and when the empty line is entered I need to print all first characters of each line (as one word). Can somebody explain what should I write in the last line?

inp :: IO String
inp
   = do
      line <- getLine
      if null line
         then return ""
         else do
            lines <- inp
            return lines????
1
  • i have exam in two days and i am preparing for it. It is true. Believe or not. and i need help Commented May 21, 2012 at 18:18

1 Answer 1

3

I don't want to spoil everything, but here are a few hints:

  1. String is actually just another name for [Char].
  2. You can construct a new list that's just like an old one, but with a new element tacked onto the front with the (:) :: a -> [a] -> [a] function (and in particular, (:) :: Char -> String -> String). You can read this function aloud as "cons". For example, 1:[2,3,4] is the same as [1,2,3,4], and 'a':"bcd" is the same as "abcd".
  3. When you're certain a list isn't empty, you can ask for its first element with the head :: [a] -> a function (and in particular, head :: String -> Char).
  4. As an alternative strategy, you might want to look into pattern matching instead of using null and if/then/else; this also eliminates the need for head, which is often a code smell.

From a comment, you've also tried something like this as your last line:

return head(lines) : []

The main problem here is that return is not a keyword in Haskell, it's just a plain old function. So if your argument is an expression, you need to parenthesize it (or use one of the various tricks for avoiding parentheses):

return (head(lines) : [])
return (head lines : [])
return $ head lines : []
return [head lines]
let answer = head lines : [] in return answer

etc. This should get you to where things typecheck and run; then you can get started correcting the bugs in the behavior of the code. =)

Sign up to request clarification or add additional context in comments.

3 Comments

thats very good, but i still do not know what to write in the last line, because i am getting errors while compiling the code.
@Bob If you have something you've tried that didn't work, you should tell us the exact code you tried and the exact error you got.
for example: return head(lines) : [] last line. and the error is Couldn't match expected type IO String' with actual type [a0]'