CSV.hs 1.15 KB
Newer Older
1
module CSV where
pm3g19's avatar
pm3g19 committed
2
3

import System.IO
4
import Data.List
pm3g19's avatar
pm3g19 committed
5
6
7
8
9
10
11

readCSV :: FilePath -> IO [[String]]
readCSV fname = do
    str <- readFile fname
    return $ readCSVString str

readCSVString :: String -> [[String]]
mnay1u19's avatar
mnay1u19 committed
12
readCSVString whole = [splitElem ',' (line++" " )  | line <- splitElem '\n' whole]
pm3g19's avatar
pm3g19 committed
13
14
15
16
17
18
19
splitElem :: Eq a => a -> [a] -> [[a]]
splitElem elem = split (/=elem)

split :: (a -> Bool) -> [a] -> [[a]]
split p l = case span p l of
        ([], _) -> []
        (match, []) -> [match]
20
        (match, _:rem') -> match:split p rem'
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

print2DList :: [[String]] -> IO ()
print2DList = putStrLn.toCSVString

toCSVString :: [[String]] -> String
--F: use the function lines!
toCSVString list = let lines = map (',' `join`) list in '\n' `join` lines

join :: a -> [[a]] -> [a]
join _ [] = []
join a l = foldr1 (\s1 s2 -> s1 ++ a:s2) l

sort2DListLex :: [[String]] -> [[String]]
sort2DListLex = sort

stripWhitespace = stripTrailingWhitespace.dropWhile (==' ')

stripTrailingWhitespace (' ':xs) = let remainder = stripTrailingWhitespace xs in
    if null remainder then [] else ' ':remainder

stripTrailingWhitespace (x:xs) = x : stripTrailingWhitespace xs
stripTrailingWhitespace [] = []