Reputation: 964
Is there any fast way in Haskell to cast an input file like that into corresponding types? For example a function that takes a string and produces a list of Int
s? Or do I need to parse it manually using getLine
and parse the string?
10.
10.
[4, 3, 2, 1].
[(5,8,'~'), (6,4,'*'), (7,10,'~'), (8,2,'o')].
[4,0,9,4,7,5,7,4,6,4].
[4,10,0,6,6,5,6,5,6,2].
Upvotes: 2
Views: 3460
Reputation: 35089
To build on Jeff Burka's answer, here's the specific code you would use for your particular file:
main = do
[l1, l2, l3, l4, l5, l6] <- fmap (map init . lines) $ readFile "myFile.txt"
let myVal :: (Int, Int, [Int], [(Int, Int, Char)], [Int], [Int])
myVal = (read l1, read l2, read l3, read l4, read l5, read l6)
print myVal
This will print out the parsed tuple.
The init
part is to get rid of the trailing period you have at the end of each line.
Upvotes: 4
Reputation: 2571
Yes, the read
function.
Once you read in the file with readFile
for example, you can read
each line to convert it to the type you want. You'll have to get rid of the periods first, though. So for example:
main = do
text <- readFile "test.txt"
let cases = lines text
-- to get rid of the periods at the end of each line
strs = map init cases
lastLine = read $ last strs
print $ show (map (+5) lastLine)
This will take your example file and read in a list of Int
s from the last line, and the add 5 to the whole list and print it.
If every line were the same type, you could just map read
over all the lines to get all of them. If there are different types, like in your example, you'd have to put in some logic to figure out what type is on each line, and then call an appropriate function to deal with that type.
Upvotes: 6