I have a list with a string inside it and I need to have that deconstructed Char by Char and put into a list as Integer instead but I’m stymied by the types
What i have is a txt file that i read into monad:
getTxt = do
y <- readFile "foo.txt"
return y
foo only contains this:
"1234567890\n"
then I thought I was close with sequence but that gets me this list:
["1","2","3","4","5","6","7","8","9","0"] :: [[Char]]
but I need [Integer]. ord will take Char -> Int but how do I read that [Char] -> [Int] ? And after all these trial and only error, don’t I need to filter out that last new line in the end?
Any suggestions?
If you use
ord, the types match, but it’s not what you want becauseordgives youthe ascii value, not the numeric value:
ord 5is53, not5. You could subtract48 to get the digit, then roll the digits up into a single number, but it would be
easier to use a library function. The most straightforward choice is
read:As in the linked answer,
the best solution here is to use
reads.readsfinds a list of possible matches,as pairs of
(match,remainingstring),which works well for you because it will automatically leave the newline in the remaining string,
*Main> reads "31324542\n" :: [(Integer,String)][(31324542,"\n")]Let’s use that:
Maybe‘s a handy data type that lets you have failure without crashing the program or doing exception handling.Just 5means you got output and it’s5.Nothingmeans there was a problem, no output.Which gives you:
*Main> addTen "foo.txt"Added 10, got 1234567890If you just want the integers the characters represent, you can put
import Data.Charat the top of your file and doThis takes the characters of the string
yfor as long as they’re digits,then finds their
ord, subtractingord '0'(which is 48) to turn'4'into4etc.