summaryrefslogtreecommitdiff
path: root/hs/Util.hs
blob: 54a334e45ab9a61526959a6e5beff5c6c402ca4c (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
module Util
( accumulate
, intersperse
, joinBy
, (&)
, nullToMaybe
, firstJust
) where

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

(&) = flip ($)


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