Reputation: 535
I am trying to practise declarative programming using Haskell, I am running into some confusion with the interact function.
I can see from its type signature it operates on a whole string at once:
interact :: (String -> String) -> IO ()
What is the value of the string for a multiline input? I assume that it is a single string with a newline character inside of it?
For a Haskell program Main.hs
module Main where
main :: IO ()
main = interact( ... )
and a input file input.txt
5 6 7
3 6 10
If I run the compiled program like this:
$ Main < input.txt
Would the string that the interact is working with be:
5 6 7\n3 6 10
Upvotes: 2
Views: 322
Reputation: 476493
It will pass "5 6 7\n3 6 10\n"
as string. We can easily verify that by using show
as function:
main = interact show
If we then call the progam with I/O redirection, we get:
./Main < data.dat
"5 6 7\n3 6 10\n"
You can make use of lines :: String -> [String]
to convert the String
to a list of String
s where each string is a line. If we change the program to:
main = interact (show . lines)
we see:
./Main < data.dat
["5 6 7","3 6 10"]
So by using lines
in this case, we retrieve a list of two elements "5 6 7"
, and "3 6 9"
.
Upvotes: 3