0 | module Control.Lens.Optional
2 | import Data.Profunctor
3 | import Control.Lens.Optic
4 | import Control.Lens.Indexed
5 | import Control.Lens.Lens
6 | import Control.Lens.Prism
17 | record IsOptional p where
18 | constructor MkIsOptional
19 | runIsOptional : (Strong p, Choice p)
22 | optionalToLens : IsOptional p => IsLens p
23 | optionalToLens @{MkIsOptional _} = MkIsLens %search
26 | optionalToPrism : IsOptional p => IsPrism p
27 | optionalToPrism @{MkIsOptional _} = MkIsPrism %search
30 | indexedOptional : IsOptional p => IsOptional (Indexed i p)
31 | indexedOptional @{MkIsOptional _} = MkIsOptional %search
37 | 0 Optional : (s,t,a,b : Type) -> Type
38 | Optional = Optic IsOptional
42 | 0 Optional' : (s,a : Type) -> Type
43 | Optional' = Simple Optional
47 | 0 IndexedOptional : (i,s,t,a,b : Type) -> Type
48 | IndexedOptional = IndexedOptic IsOptional
52 | 0 IndexedOptional' : (i,s,a : Type) -> Type
53 | IndexedOptional' = Simple . IndexedOptional
63 | optional : (s -> Either t a) -> (s -> b -> t) -> Optional s t a b
64 | optional prj set @{MkIsOptional _} = dimap @{fromStrong}
65 | (\s => (prj s, set s))
66 | (\(e, f) => either id f e)
70 | fromStrong : Strong p => Profunctor p
71 | fromStrong = %search
75 | optional' : (s -> Maybe a) -> (s -> b -> s) -> Optional s s a b
76 | optional' prj = optional (\x => maybe (Left x) Right (prj x))
80 | ioptional : (s -> Either t (i, a)) -> (s -> b -> t) -> IndexedOptional i s t a b
81 | ioptional prj set @{_} @{ind} = optional prj set . indexed @{ind}
85 | ioptional' : (s -> Maybe (i, a)) -> (s -> b -> s) -> IndexedOptional i s s a b
86 | ioptional' prj = ioptional (\x => maybe (Left x) Right (prj x))
91 | ignored : IndexedOptional i s s a b
92 | ignored = ioptional' (const Nothing) const
104 | filtered : (a -> Bool) -> Optional' a a
105 | filtered p = optional' (\x => if p x then Just x else Nothing) (const id)
110 | getOptional : Optional s t a b -> (s -> Either t a, s -> b -> t)
111 | getOptional l = l @{MkIsOptional (strong,choice)} (Right, const id)
113 | Profunctor (\x,y => (x -> Either y a, x -> b -> y)) where
114 | dimap f g (prj, set) = (either (Left . g) Right . prj . f, (g .) . set . f)
116 | [strong] GenStrong Pair (\x,y => (x -> Either y a, x -> b -> y)) where
117 | strongl (prj, set) = (\(a,c) => mapFst (,c) (prj a), \(a,c),b => (set a b, c))
118 | strongr (prj, set) = (\(c,a) => mapFst (c,) (prj a), \(c,a),b => (c, set a b))
120 | [choice] GenStrong Either (\x,y => (x -> Either y a, x -> b -> y)) where
121 | strongl (prj, set) = (either (either (Left . Left) Right . prj) (Left . Right),
122 | \e,b => mapFst (`set` b) e)
123 | strongr (prj, set) = (either (Left . Left) (either (Left . Right) Right . prj),
124 | \e,b => mapSnd (`set` b) e)
128 | withOptional : Optional s t a b -> ((s -> Either t a) -> (s -> b -> t) -> r) -> r
129 | withOptional l f = uncurry f (getOptional l)
134 | matching : Optional s t a b -> s -> Either t a
135 | matching = fst . getOptional