blob: 61df8da19d17ef78ba66ede3c2997ab272d7960c (
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
|
module JoinList where
data JoinList m a = Empty
| Single m a
| Append m (JoinList m a) (JoinList m a)
deriving (Eq, Show)
-- Exercise 1
tag :: Monoid m => JoinList m a -> m
tag Empty = mempty
tag Single m _ = m
tag Append m _ _ = m
(+++) :: Monoid m => JoinList m a -> JoinList m a -> JoinList m a
(+++) jl1 jl2 = mappend jl1 jl2
-- Exercise 2
indexJ :: (Sized b, Monoid b) => Int -> JoinList b a -> Maybe a
indexJ _ Empty = Nothing
indexJ n (Single _ a)
| n == 0 = Just a
| otherwise = Nothing
indexJ n (Append m jl1 jl2)
| n < 0 || n >= m = Nothing
| n < tag1 = indexJ n jl1
| n >= tag1 = indexJ (n - tag1) jl2
where tag1 = tag jl1
dropJ :: (Sized b, Monoid b) => Int -> JoinList b a -> JoinList b a
dropJ _ Empty = Empty
dropJ n jl
| n <= 0 = jl
dropJ n (Single _ _)
| n >= 1 = Empty
dropJ n (Append m jl1 jl2)
| n >= m = Empty
| n >= tag1 = jl2
where tag1 = tag jl1
|