-
Notifications
You must be signed in to change notification settings - Fork 0
/
FTree.hs
60 lines (32 loc) · 1.57 KB
/
FTree.hs
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
59
{-# OPTIONS_GHC -XNPlusKPatterns #-}
-- (c) MP-I (1998/9-2006/7) and CP (2005/6-2018/9)
module FTree where
import Cp
-- (1) Datatype definition -----------------------------------------------------
data FTree a c = Unit c | Comp a (FTree a c, FTree a c) deriving Show
inFTree = either Unit (uncurry Comp)
outFTree (Unit c) = Left c
outFTree (Comp a (t1,t2)) = Right(a,(t1,t2))
baseFTree f g h = f -|- (g >< (h >< h))
-- (2) Ana + cata + hylo -------------------------------------------------------
cataFTree a = a . (recFTree (cataFTree a)) . outFTree
anaFTree f = inFTree . (recFTree (anaFTree f) ) . f
hyloFTree a c = cataFTree a . anaFTree c
recFTree f = baseFTree id id f
-- (3) Map ---------------------------------------------------------------------
instance BiFunctor FTree
where bmap f g = cataFTree ( inFTree . baseFTree g f id )
-- (4) Examples ----------------------------------------------------------------
-- (4.1) Inversion (mirror) ----------------------------------------------------
invFTree = cataFTree (inFTree . (id -|- id >< swap))
-- (4.2) Counting --------------------------------------------------------------
countFTree = cataFTree (either (const 1) (succ . (uncurry (+)) . p2))
-- (4.3) Flattening ------------------------------------------------------------
flatFTree = cataFTree flt
flt = either singl (cons.(id><conc))
-- (4.4) Generating lists of Booleans ------------------------------------------
genBoolTree = anaFTree gbt
gbt = f where
f(0,x)=i1 x
f(n+1,x) = i2(x,((n,False:x),(n,True:x)))
genBools = hyloFTree flt gbt