1
votes

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?

2
I have trouble understanding the question - but you know that String is just [Char]?Random Dev
can you please post the file content and what your expected answer should be?Random Dev
Yes String is just [Char] but but I get make double list, where each line of text is a list that is part of another listMerche
you get the wrapped Strings because you did the double map there - can you please edit your question and provide the input and the expected output? I really have trouble if your input is supposed to be "a10b\ndot2" or if this is the expected outuptRandom Dev

2 Answers

2
votes

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!

0
votes

[[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 [[...]]