@@ -10,7 +10,7 @@ Example adapted from SYB
11module Main (main) where
11module Main (main) where
13−import Control.Lens.Fold (toListOf)
13+import Control.Lens
14import Control.Monad (void)
14import Control.Monad (void)
15import Data.Generics.Product
15import Data.Generics.Product
16import GHC.Generics
16import GHC.Generics
@@ -23,22 +23,48 @@ main = void $ runTestTT tests
23data Tree a w = Leaf a
23data Tree a w = Leaf a
24 | Fork (Tree a w) (Tree a w)
24 | Fork (Tree a w) (Tree a w)
25 | WithWeight (Tree a w) w
25 | WithWeight (Tree a w) w
26− deriving (Show, Generic)
26+ deriving (Show, Generic, Eq)
28-- A typical tree
28-- A typical tree
29mytree :: Tree Int Int
29mytree :: Tree Int Int
30mytree = Fork (WithWeight (Leaf 42) 1)
30mytree = Fork (WithWeight (Leaf 42) 1)
31 (WithWeight (Fork (Leaf 88) (Leaf 37)) 2)
31 (WithWeight (Fork (Leaf 88) (Leaf 37)) 2)
33+mytreeShown :: Tree String Int
34+mytreeShown = Fork (WithWeight (Leaf "42") 1)
35+ (WithWeight (Fork (Leaf "88") (Leaf "37")) 2)
37+-- A polymorphic-recursive structure
41+ deriving (Show, Generic)
43+poly :: Poly Int String
44+poly = PCons 10 (PCons "hello" (PCons 20 (PCons "world" PNil)))
33-- Print everything like an Int in mytree
46-- Print everything like an Int in mytree
34-- In fact, we show two attempts:
47-- In fact, we show two attempts:
35-- 1. print really just everything like an Int
48-- 1. print really just everything like an Int
36-- 2. print everything wrapped with Leaf
49-- 2. print everything wrapped with Leaf
37-- So (1.) confuses leafs and weights whereas (2.) does not.
50-- So (1.) confuses leafs and weights whereas (2.) does not.
38tests :: Test
51tests :: Test
53+ [ toListOf (typesDeep @Int) mytree ~=? [42,1,88,37,2]
54+ , toListOf (param @1) mytree ~=? [42,88,37]
56+ -- Things not (easily) doable in SYB:
57+ -- change type of Tree by mapping a function over the second (from the right) param
58+ , (mytree & param @1 %~ show) ~=? mytreeShown
59+ -- collect values in poly corresponding to the first param
60+ , toListOf (param @0) poly ~=? ["hello", "world"]
61+ -- collect all Ints inside poly
39−tests = show ( toListOf (typesDeep @Int) mytree
62+ , toListOf (typesDeep @Int) poly ~=? [10, 20]
63+ -- map length over the Strings, then collect all Ints
40− , toListOf (param @1) mytree
64+ , toListOf (typesDeep @Int) (poly & param @0 %~ length) ~=? [10, 5, 20, 5]
41− ) ~=? output
65+ -- map length over the Strings, then collect all the resulting Ints
66+ , toListOf (param @0) (poly & param @0 %~ length) ~=? [5,5]
43-- original code from SYB:
69-- original code from SYB:
44--tests = show ( listify (\(_::Int) -> True) mytree
70--tests = show ( listify (\(_::Int) -> True) mytree
@@ -48,6 +74,3 @@ tests = show ( toListOf (typesDeep @Int) mytree
48-- fromLeaf :: Tree Int Int -> [Int]
74-- fromLeaf :: Tree Int Int -> [Int]
49-- fromLeaf (Leaf x) = [x]
75-- fromLeaf (Leaf x) = [x]
50-- fromLeaf _ = []
76-- fromLeaf _ = []
53−output = "([42,1,88,37,2],[42,88,37])"