]> Git — Sourcephile - comptalang.git/blob - cli/Hcompta/Lib/Data/Text.hs
Refactor hcompta-lib.
[comptalang.git] / cli / Hcompta / Lib / Data / Text.hs
1 {-# LANGUAGE FlexibleInstances #-}
2 {-# LANGUAGE OverloadedStrings #-}
3 {-# LANGUAGE ViewPatterns #-}
4 {-# OPTIONS_GHC -fno-warn-tabs #-}
5 {-# OPTIONS_GHC -fno-warn-orphans #-}
6 module Hcompta.Lib.Data.Text where
7
8 import Data.Char (Char)
9 import Data.Eq (Eq(..))
10 import qualified Data.List as List
11 import Data.Maybe (Maybe(..))
12 import Data.String (String)
13 import Data.Text (Text)
14 import qualified Data.Text as Text
15
16 -- * Class 'SplitOnChar'
17
18 class SplitOnChar t where
19 splitOnChar :: Char -> t -> [t]
20 instance SplitOnChar Text where
21 splitOnChar sep t =
22 case Text.uncons t of
23 Nothing -> []
24 Just (x, xs) ->
25 if x == sep
26 then splitOnChar sep xs
27 else
28 let (chunk, rest) = Text.break (== sep) t in
29 chunk:splitOnChar sep rest
30 instance SplitOnChar String where
31 splitOnChar sep t =
32 case t of
33 [] -> []
34 x:xs ->
35 if x == sep
36 then splitOnChar sep xs
37 else
38 let (chunk, rest) = List.break (== sep) t in
39 chunk:splitOnChar sep rest
40
41 -- * Class 'SplitOnCharWithEmpty'
42
43 class SplitOnCharWithEmpty t where
44 splitOnCharWithEmpty :: Char -> t -> [t]
45 instance SplitOnCharWithEmpty Text where
46 splitOnCharWithEmpty sep t =
47 case Text.break (== sep) t of
48 (chunk, Text.uncons -> Just (_, rest)) -> chunk : splitOnCharWithEmpty sep rest
49 (chunk, _) -> [chunk]
50 instance SplitOnCharWithEmpty String where
51 splitOnCharWithEmpty sep t =
52 case List.break (== sep) t of
53 (chunk, _:rest) -> chunk : splitOnCharWithEmpty sep rest
54 (chunk, []) -> [chunk]