Not particularly great with Haskell here. Just getting started with I/O with Haskell
I have a CSV file with a single column with numbers as follows:
I have a function that takes in the name of the file and prints out a single list containing lists for each line of the CSV of type:
printList :: String -> IO ()
printList nameOfinputFile = do
s <- readFile inp
..................
..................
..................
print (splitList)
where splitList is the intended output and for the given CSV file example, and it's meant to look like:
[ [1,2,3],[4,5],[6,7,8,9],[10],[11,12,13,14,15],[16],[17] ]
How can I implement this while preserving the type of my function?
CodePudding user response:
This works on Replit:
import Data.List(lines)
import Distribution.Simple.Utils(unintersperse)
splitList :: String -> [[Int]]
splitList = map (map read . unintersperse ',') . lines
CodePudding user response:
There are likely to be many ways of doing the same thing. This is my version:
import Data.List.Split
convList [] = []
convList [""] = []
convList xs = map (\x -> read x :: Int) xs
main = do
content <- readFile "Test.csv"
let valuesStr = map (splitOn ",") $ lines content
let valuesInt = map convList valuesStr
print valuesInt
The main function uses readFile
to slurp in the CSV file. The function lines
is used to split the content, and then splitOn
is mapped over the lines. Finally, a new function convList
is mapped over the values inside each list. The function convList
has three possibilities:
- Empty list, yields an empty list
- Blank line, yields an empty list
- Elements exist, yields values (here Int, could be Double)
Result with extra blank line:
[[1,2,3],[4,5],[6,7,8,9],[10],[11,12,13,14,15],[16],[17],[]]