@@ -10,7 +10,7 @@ Example adapted from SYB
1010
1111module Main (main) where
1212
13−import Control.Lens.Fold (toListOf)
13+import Control.Lens
1414import Control.Monad (void)
1515import Data.Generics.Product
1616import GHC.Generics
@@ -23,22 +23,48 @@ main = void $ runTestTT tests
2323data Tree a w = Leaf a
2424 | Fork (Tree a w) (Tree a w)
2525 | WithWeight (Tree a w) w
26− deriving (Show, Generic)
26+ deriving (Show, Generic, Eq)
2727
2828-- A typical tree
2929mytree :: Tree Int Int
3030mytree = Fork (WithWeight (Leaf 42) 1)
3131 (WithWeight (Fork (Leaf 88) (Leaf 37)) 2)
3232
33+mytreeShown :: Tree String Int
34+mytreeShown = Fork (WithWeight (Leaf "42") 1)
35+ (WithWeight (Fork (Leaf "88") (Leaf "37")) 2)
36+
37+-- A polymorphic-recursive structure
38+data Poly a b
39+ = PNil
40+ | PCons a (Poly b a)
41+ deriving (Show, Generic)
42+
43+poly :: Poly Int String
44+poly = PCons 10 (PCons "hello" (PCons 20 (PCons "world" PNil)))
45+
3346-- Print everything like an Int in mytree
3447-- In fact, we show two attempts:
3548-- 1. print really just everything like an Int
3649-- 2. print everything wrapped with Leaf
3750-- So (1.) confuses leafs and weights whereas (2.) does not.
3851tests :: Test
39−tests = show ( toListOf (typesDeep @Int) mytree
40− , toListOf (param @1) mytree
41− ) ~=? output
52+tests = TestList
53+ [ toListOf (typesDeep @Int) mytree ~=? [42,1,88,37,2]
54+ , toListOf (param @1) mytree ~=? [42,88,37]
55+
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
62+ , toListOf (typesDeep @Int) poly ~=? [10, 20]
63+ -- map length over the Strings, then collect all Ints
64+ , toListOf (typesDeep @Int) (poly & param @0 %~ length) ~=? [10, 5, 20, 5]
65+ -- map length over the Strings, then collect all the resulting Ints
66+ , toListOf (param @0) (poly & param @0 %~ length) ~=? [5,5]
67+ ]
4268
4369-- original code from SYB:
4470--tests = show ( listify (\(_::Int) -> True) mytree
@@ -48,6 +74,3 @@ tests = show ( toListOf (typesDeep @Int) mytree
4874-- fromLeaf :: Tree Int Int -> [Int]
4975-- fromLeaf (Leaf x) = [x]
5076-- fromLeaf _ = []
51−
52−output :: String
53−output = "([42,1,88,37,2],[42,88,37])"