1

I'm new to Haskell. I try to make some exercice and one of this is to ask a number n, then get n and concatenate them. the prototype of the function is given by the exercise:

concatLines :: Int -> IO String

I tryied this/

concatLines n   | n == 1 = getLine >>= \x -> return x
                | otherwise = getLine >>= \x -> return $ (x ++ concatLines (n - 1))

But i got the following error:

DoOp.hs:63:64:
    Couldn't match expected type \`[Char]\` with actual type \`IO String\`
    In the return type of a call of \`concatLines\`
    In the second argument of \`(++)\`, namely \`concatLines (n - 1)\`
    In the second argument of \`($)\`, namely
      (x ++ concatLines (n - 1))\`

I search for convert IO String to [Char] but without succes.

amalloy
  • 89,153
  • 8
  • 140
  • 205
DipStax
  • 343
  • 2
  • 12
  • 1
    This has been asked in the questions I linked and many more. To make it short, you never want to convert `IO a` to `a`, what you should actually do is _bind it_ in the monad, normally most convenient with `do` notation. – leftaroundabout Jan 27 '21 at 13:58
  • As the error message tells you, `concatLines (n - 1)` returns `IO String`, which doesn't support the `++` operator. You may consider using monadic bind (`>>=`) once more. – Mark Seemann Jan 27 '21 at 13:58
  • In this case you basically just need to omit a `return`, but the key is understanding what the monadic primitives actually accomplish. – leftaroundabout Jan 27 '21 at 13:59
  • `concatLines n = concat <$> replicateM n getLine`, where `replicateM` comes from `Control.Monad`. – chepner Jan 27 '21 at 14:34

0 Answers0