macropy icon indicating copy to clipboard operation
macropy copied to clipboard

Lenses

Open lihaoyi opened this issue 11 years ago • 4 comments

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.

lihaoyi avatar May 15 '13 12:05 lihaoyi

I really like this, actually.

jnhnum1 avatar May 17 '13 23:05 jnhnum1

Do you have any experience using these in Haskell? IIRC that's where the idea originated from

lihaoyi avatar May 18 '13 02:05 lihaoyi

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.

jnhnum1 avatar May 18 '13 03:05 jnhnum1

these would fit in nicely in FunPy too, along with case classes, when we do the eventual modularization

lihaoyi avatar May 18 '13 03:05 lihaoyi