I am solving Project Euler Problem 11. I have copy-pasted the table in the problem into a file called “input.txt”. Each line of the input file contains a row of a 20×20 matrix, and the columns are separated by whitespace.
What I want is a function that reads this file, and returns it as an IO Array. I’m having huge trouble doing this.
So far I’ve done this:
import System.IO
import Control.Monad
main = readFile "input.txt"
This of course only gives me the IO String representation of the input file, but everything I try seems to fail. How should I proceed? I know I should do something like
array ((1,1),(20,20)) [ the numbers tupled with their indices ]
but converting the numbers is outright impossible for me, most likely because I do not entirely understand monads yet.
I am confident that this is in fact quite easy, once you understand it.
Does anyone have a suggestion about what to do?
You can parse your file with something like this:
By combining
wordswithmap read(whereread :: (Read a) => String -> a) you get a list[Int].So, in order to organize things a little bit, your code in the IO monad may look like this (assuming that every row has the same fixed number of columns and that you take the input file name, the number of rows and of columns as commandline arguments):
Note how the conversion function
readWordsis able to convert to any[a]provided thatRead a, so that we don’t restrict ourselves to integers only.The
liftMfunction takes a pure function (ourreadWords) and “lifts” it to work in the current monad, i.e.IO.