3 | import Monocle.Getter
4 | import Monocle.Optional
5 | import Monocle.Setter
6 | import Monocle.Traversal
7 | import Control.Monad.State
8 | import Data.List.Quantifiers.Extra
11 | import Data.SortedMap
32 | record Lens (s,t,a,b : Type) where
35 | mod_ : (a -> b) -> s -> t
40 | 0 Lens' : (s,a : Type) -> Type
41 | Lens' s a = Lens s s a a
46 | lens : (s -> a) -> (b -> s -> t) -> Lens s t a b
47 | lens f g = L f $
\h,v => g (h $
f v) v
55 | interface ToLens (0 o : Type -> Type -> Type -> Type -> Type) where
56 | toLens : o s t a b -> Lens s t a b
58 | public export %inline
59 | ToLens Lens where toLens = id
66 | public export %inline
67 | setL : Lens s t a b -> b -> s -> t
68 | setL l = mod_ l . const
72 | public export %inline
73 | modF : Functor f => Lens s t a b -> (a -> f b) -> s -> f t
74 | modF l g v = (\x => setL l x v) <$> g (get_ l v)
78 | (~>) : Lens s t x y -> Lens x y a b -> Lens s t a b
79 | L g1 s1 ~> L g2 s2 = L (g2 . g1) (s1 . s2)
85 | public export %inline
89 | public export %inline
91 | toFold = toFold . toGetter
94 | ToOptional Lens where
95 | toOptional l = O (Right . l.get_) l.mod_
97 | public export %inline
101 | public export %inline
102 | ToTraversal Lens where
103 | toTraversal l = T (modF l) (toFold l) (toSetter l)
110 | public export %inline
111 | fst : Lens (a,c) (b,c) a b
116 | snd : Lens (c,a) (c,b) a b
121 | head : Lens' (Vect (S n) a) a
122 | head = lens head $
\x,v => x :: tail v
126 | tail : Lens' (Vect (S n) a) (Vect n a)
127 | tail = lens tail $
\x,v => head v :: x
131 | ix : Fin n -> Lens' (Vect n a) a
132 | ix x = L (index x) (updateAt x)
136 | head1 : Lens' (List1 a) a
137 | head1 = lens head $
\x,v => x ::: tail v
141 | tail1 : Lens' (List1 a) (List a)
142 | tail1 = lens tail $
\x,v => head v ::: x
151 | at : Ord k => k -> Lens' (SortedMap k v) (Maybe v)
152 | at x = lens (lookup x) $
\mv,m => maybe (delete x m) (\v => insert x v m) mv
157 | atDflt : Ord k => k -> v -> Lens' (SortedMap k v) v
158 | atDflt x v = lens (fromMaybe v . lookup x) (insert x)
163 | atAuto : Ord k => k -> {auto prf : v} -> Lens' (SortedMap k v) v
164 | atAuto x = atDflt x prf
169 | -> {0 f : k -> Type}
170 | -> {auto e : Elem t ks}
173 | allGet @{Here} (h::_) = h
174 | allGet @{There _} (_::vs) = allGet vs
179 | -> {0 f : k -> Type}
180 | -> {auto e : Elem t ks}
184 | allUpd @{Here} g (h::vs) = g h :: vs
185 | allUpd @{There _} g (h::vs) = h :: allUpd g vs
191 | -> {0 f : k -> Type}
193 | -> {auto e : Elem t ks}
194 | -> Lens' (All f ks) (f t)
195 | prod t = L allGet allUpd
198 | allHead : Lens' (All f (k::ks)) (f k)
199 | allHead = lens (\(v::_) => v) (\v,(_::vs) => v::vs)
202 | allTail : Lens' (All f (k::ks)) (All f ks)
203 | allTail = lens (\(_::vs) => vs) (\vs,(v::_) => v::vs)
211 | stL : Functor m => Lens' t s -> StateT s m x -> StateT t m x
212 | stL l (ST f) = ST $
\v => (\(w,r) => (setL l w v, r)) <$> f (l.get_ v)