Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell way to join [IO String] into IO String

Tags:

io

haskell

monads

my goal is to write Haskell function which reads N lines from input and joins them in one string. Below is the first attempt:

readNLines :: Int -> IO String
readNLines n = do
  let rows = replicate n getLine
  let rowsAsString = foldl ++ [] rows 
  return rowsAsString  

Here haskell complaints on foldl:

Couldn't match expected type [a]' against inferred type(a1 -> b -> a1) -> a1 -> [b] -> a1'

As I understand type of rows is [IO String], is it possible some how join such list in a single IO String?

like image 691
Peter Popov Avatar asked Nov 28 '22 07:11

Peter Popov


2 Answers

You're looking for sequence :: (Monad m) => [m a] -> m [a].

(Plus liftM :: Monad m => (a1 -> r) -> m a1 -> m r and unlines :: [String] -> String, probably.)

like image 54
ephemient Avatar answered Dec 04 '22 08:12

ephemient


Besides what ephemient points out, I think you have a syntax issue: The way you're using the ++ operator makes it look like you are trying to invoke the ++ operator with operands foldl and []. Put the ++ operator in parentheses to make your intent clear:

foldl (++) [] rows
like image 26
Daniel Pratt Avatar answered Dec 04 '22 08:12

Daniel Pratt