summaryrefslogtreecommitdiff
path: root/hs/src/Util.hs
blob: e3c8d2fc758f9cfacfc085a30c8e74d4746002df (plain)
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
module Util
( accumulate
, intersperse
, joinBy
, nullToMaybe
, firstJust
, splitBy
) where

swap :: (a, b) -> (b, a)
swap (a, b) = (b, a)

-- Accumulate all sub-sequences,
-- For example, accumulate [1,2,3] == [[1], [1, 2], [1, 2, 3]]
accumulate :: [a] -> [[a]]
accumulate [] = []
accumulate (x:xs) = (x:) <$> ([]:accumulate xs)

-- Insert element at every other position of list
intersperse :: a -> [a] -> [a]
intersperse _ [] = []
intersperse _ [x] = [x]
intersperse y (x:xs) = x : y : intersperse y xs

joinBy :: Monoid a => a -> [a] -> a
joinBy delim lst = mconcat $ intersperse delim lst

splitBy' :: Eq a => a -> [a] -> ([a], [a])
splitBy' _ [] = ([], [])
splitBy' delim (x:xs)
    | delim == x = (xs, [])
    | otherwise = (x:) <$> splitBy' delim xs

splitBy :: Eq a => a -> [a] -> ([a], [a])
splitBy d = swap . splitBy' d

nullToMaybe :: (Eq a, Monoid a) => a -> Maybe a
nullToMaybe m
    | m == mempty = Nothing
    | otherwise   = Just m


firstJust :: a -> [Maybe a] -> a
firstJust x [] = x
firstJust _ (Just x:_) = x
firstJust x (_:xs) = firstJust x xs