Merche
Merche

Reputation: 129

haskell read a file and convert it map of list

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

Answers (2)

Random Dev
Random Dev

Reputation: 52290

one solution

convert :: String -> [[String]]
convert = map (map return) . lines

should do the trick

remark

the return here is a neat trick to write \c -> [c] - wrapping a Char into a singleton list as lists are a monad

how it works

Let me try to explain this:

  • lines will split the input into lines: [String] which each element in this list being one line
  • the outer map (...) . lines will then apply the function in (...) to each of this lines
  • the function inside: map 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 characters
  • now return here will just take a character and put it into a singleton list: 'a' -> [a] = "a" which is exactly what you wanted

your example

Prelude> 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"]]

concerning your comment

if you expect convert :: String -> [[Char]] (which is just String -> [String] then all you need is convert = lines!

Upvotes: 2

karakfa
karakfa

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

Related Questions