Skip to content

Instantly share code, notes, and snippets.

@Keno
Created August 19, 2020 02:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Keno/0e8998cdf9da1bc61b55317819855005 to your computer and use it in GitHub Desktop.
Save Keno/0e8998cdf9da1bc61b55317819855005 to your computer and use it in GitHub Desktop.
# Generic Optic definition
abstract type AbstractOptic; end
struct OpticRepr <: AbstractOptic
l::Function
r::Function
end
OpticRepr(o::OpticRepr) = o
OpticRepr(o::AbstractOptic) =
OpticRepr(a->left(o, a),
(m, b′)->right(o, m, b′))
left(o::OpticRepr, a) = o.l(a)
right(o::OpticRepr, m, b′) = o.r(m, b′)
function ⨟(o₁::AbstractOptic, o₂::AbstractOptic)
OpticRepr(
function (a)
x = left(o₁, a)
y = left(o₂, x[2])
(x[1], y[1]), y[2]
end,
((m₁, m₂), c′)->right(o₁, m₁, right(o₂, m₂, c′))
)
end
function (o::AbstractOptic)(f::Function, a)
m, b = left(o, a)
b′ = f(b)
right(o, m, b′)
end
# Continuation style optics interface
function (o::AbstractOptic)(a)
m, b = left(o, a)
b, b′->right(o, m, b′)
end
# Back functor
struct Back <: AbstractOptic
prim
end
function left(bb::Back, a)
(a, bb.prim(a))
end
function right(b::Back, m, b′)
(b′..., (Symbol(b.prim), m))
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment