macropy
macropy copied to clipboard
Lenses
Macro Lenses could allow really nice nested updates of immutable hierarchical structures. Like:
# tree for the source code (~1 + (2 + 3))
x = BinOp(
left=UnaryOp(
op=Invert(),
operand=Num(n=1)
),
op=Add(),
right=BinOp(
left=Num(n=2),
op=Add(),
right=Num(n=3)
)
)
# converting it to the tree for (~3 + (2 + 3)
# without lenses
x1 = x.copy(left = x.left.copy(operand = x.left.operand.copy(n = 3)))
# with lenses
x1 = lens%x.left.operand.n.set(3)
# changing (~1 + (2 + 3)) to (~2 + (2 + 3)), by adding one to the previous value of the left item
# without lenses
x2 = x.copy(left = x.left.copy(operand = x.left.operand.copy(n = x.left.operand.n + 1)))
# with lenses
x2 = lens%x.left.operand.n.set(_ + 1)
# setting the value on the left to the sum of all values, giving (~6 + (2 + 3))
# without lenses
x3 = x.copy(left = x.left.copy(operand = x.left.operand.copy(n = x.left.operand.n + x.right.right.n + x.right.left.n)))
# with lenses
x3 = lens%x.left.operand.n.set(_ + _._.right.left.n + _._.right.right.n)
I think the last one is properly called a Zipper, but I'm not familiar enough with that branch of FP to say for sure.
I really like this, actually.
Do you have any experience using these in Haskell? IIRC that's where the idea originated from
yeah, actually I'm quite familiar with them in Haskell. I can take a shot at implementing these sometime in the next week or two.
these would fit in nicely in FunPy too, along with case classes, when we do the eventual modularization