11# # Traversal
2- # These examples are taken from the README.md of the specter clojure library.
2+ #
3+ # This code demonstrates how to use and extend advanced optics.
4+ # The examples are taken from the README.md of the specter clojure library.
35# Many of the features here are experimental, please consult the docstrings of the
46# involved optics.
57
@@ -9,30 +11,25 @@ using Accessors
911import Accessors: modify, OpticStyle
1012using Accessors: ModifyBased, SetBased, setindex
1113
14+ # ### Increment all even numbers
15+ # We have the following data and the goal is to increment all nested even numbers.
16+ data = (a = [(aa= 1 , bb= 2 ), (cc= 3 ,)], b = [(dd= 4 ,)])
17+ # To acomplish this, we define a new optic `Vals`.
1218function mapvals (f, d)
1319 Dict (k => f (v) for (k,v) in pairs (d))
1420end
1521
1622mapvals (f, nt:: NamedTuple ) = map (f, nt)
17- function mapkeys (f, d)
18- Dict (f (k) => v for (k,v) in pairs (d))
19- end
20-
21- function mapkeys (f, nt:: NamedTuple )
22- kw = map (pairs (nt)) do (key, val)
23- f (key) => val
24- end
25- (;kw... )
26- end
27-
28- struct Keys end
29- OpticStyle (:: Type{Keys} ) = ModifyBased ()
30- modify (f, obj, :: Keys ) = mapkeys (f, obj)
3123
3224struct Vals end
3325OpticStyle (:: Type{Vals} ) = ModifyBased ()
3426modify (f, obj, :: Vals ) = mapvals (f, obj)
3527
28+ # Now we can increment as follows:
29+ out = @set data |> Vals () |> Elements () |> Vals () |> If (iseven) += 1
30+
31+ @test out == (a = [(aa = 1 , bb = 3 ), (cc = 3 ,)], b = [(dd = 5 ,)])
32+
3633struct Filter{F}
3734 keep_condition:: F
3835end
@@ -51,18 +48,10 @@ function modify(f, obj, optic::Filter)
5148 setindex (obj, vals, inds)
5249end
5350
54- # ### Increment all even numbers
55- data = (a = [(aa= 1 , bb= 2 ), (cc= 3 ,)], b = [(dd= 4 ,)])
56-
57- out = @set data |> Vals () |> Elements () |> Vals () |> If (iseven) += 1
58-
59- @test out == (a = [(aa = 1 , bb = 3 ), (cc = 3 ,)], b = [(dd = 5 ,)])
6051
6152# ### Append to nested vector
6253data = (a = 1 : 3 ,)
63-
64- optic = @optic _. a
65- out = modify (v -> vcat (v, [4 ,5 ]), data, optic)
54+ out = @modify (v -> vcat (v, [4 ,5 ]), data. a)
6655
6756@test out == (a = [1 ,2 ,3 ,4 ,5 ],)
6857
0 commit comments