summaryrefslogtreecommitdiff
path: root/hs/src/Util.hs
blob: d76c5c7a4a359ea03ef71eea05148a34eff4e6a3 (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
47
48
49
50
51
52
53
54
55
56
57
58
module Util
( accumulate
, intersperse
, joinBy
, nullToMaybe
, firstJust
, splitBy
, oneOf
, uncurry3
, (<&>)
) 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

oneOf :: (a -> Bool) -> (a -> Bool) -> a -> Bool
oneOf f g x = f x || g x

uncurry3 :: (a -> b -> c -> d) -> (a, b, c) -> d
uncurry3 f (a, b, c) = f a b c

(<&>) :: Functor f => f a -> (a -> b) -> f b
(<&>) = flip (<$>)