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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
{-# LANGUAGE RankNTypes, ExistentialQuantification #-}

module Control.Scan.CSV where

import Control.Monad
import Data.Maybe

-- 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

-- some presentation-layer stuff, existentially

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

shower :: forall a. forall b. Show a => [b -> a] -> b -> [a]
shower fns thing = map (fromJust . flip ap (Just thing) . Just) fns

-- alternatively, just show me the raw value within the type
-- GIMME BYTES, BAYBEE!!!11!1!!!

class Raw r where rep :: r -> String

-- Yeah, I'm going there! Shower allows you to create uniform showable
-- types for construction of CSV-rows

data Shower = forall a. Show a => S a | forall b. Raw b => Sr b

instance Show Shower where
   show (S a) = show a
   show (Sr b) = rep b

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

-- of course, this is just an intercalate with a forall var-set, right?