Reputation: 129
input file is txt :
000011S\n
0001110\n
001G111\n
0001000\n
Result is:
[["0","0","0","0","1","1","S"], ["0","0","0","1","1","1","0"] [...]]
Read a text file with
file <- openFile nameFile ReadMode
and the final output [["a","1","0","b"],["d","o","t","2"]] is a map with list of char
try to:
convert x = map (map read . words) $ lines x
but return [[string ]]
As it could do to return the output I want? [[Char]], is there any equivalent for word but for char?
Upvotes: 1
Views: 764
Reputation: 52290
convert :: String -> [[String]]
convert = map (map return) . lines
should do the trick
the return
here is a neat trick to write \c -> [c]
- wrapping a Char
into a singleton list as lists are a monad
Let me try to explain this:
lines
will split the input into lines: [String]
which each element in this list being one linemap (...) . lines
will then apply the function in (...)
to each of this linesmap return
will again map each character of a line (remember: a String
is just a list of Char
) and will so apply return
to each of this charactersreturn
here will just take a character and put it into a singleton list: 'a' -> [a] = "a"
which is exactly what you wantedPrelude> convert "000011S\n0001110\n001G111\n0001000\n"
[["0","0","0","0","1","1","S"]
,["0","0","0","1","1","1","0"]
,["0","0","1","G","1","1","1"]
,["0","0","0","1","0","0","0"]]
if you expect convert :: String -> [[Char]]
(which is just String -> [String]
then all you need is convert = lines
!
Upvotes: 2
Reputation: 67507
[[Char]] == [String]
Prelude> map (map head) [["a","1","0","b"],["d","o","t","2"]]
["a10b","dot2"]
will fail for empty Strings though.
or map concat [[...]]
Upvotes: 0