Scanning CSV files

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
module Control.Scan.CSV where

-- I do this often enough: scanning in a CSV file, so, here it is:

-- your words function with a 'by'-argument. Should be there already ...

wordsBy :: String -> String -> [String]
wordsBy delims line =
   let isDelim = flip elem delims
   in  case dropWhile isDelim line of
            "" -> []       
            s' -> w : wordsBy delims s''
               where (w, s'') = break isDelim s'

{-- e.g.:

*Main> wordsBy "|" "REQMT209||" ~> ["REQMT209"]

*Main> wordsBy "|" "REQMT207|REQMT228, REQMT57|REQMT228, REQMT57" ~>
["REQMT207","REQMT228, REQMT57","REQMT228, REQMT57"]
--}

csv :: String -> [String]
csv = wordsBy "," -- so we could just write this.

-- Straight from Prelude.unwords using 'sep' instead of spaces as separators.

unwordsBy :: Char -> [String] -> String
unwordsBy _ [] = ""
unwordsBy _ [w] = w
unwordsBy sep (w:ws) = w ++ sep : unwordsBy sep ws

class Univ a where
   explode :: a -> [String]

uncsv :: Univ a => a -> String
uncsv = unwordsBy ',' . explode