Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lenses #24

Open
lihaoyi opened this issue May 15, 2013 · 4 comments
Open

Lenses #24

lihaoyi opened this issue May 15, 2013 · 4 comments

Comments

@lihaoyi
Copy link
Owner

lihaoyi commented May 15, 2013

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.

@jnhnum1
Copy link
Collaborator

jnhnum1 commented May 17, 2013

I really like this, actually.

@lihaoyi
Copy link
Owner Author

lihaoyi commented May 18, 2013

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

@jnhnum1
Copy link
Collaborator

jnhnum1 commented May 18, 2013

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.

@lihaoyi
Copy link
Owner Author

lihaoyi commented May 18, 2013

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants
@jnhnum1 @lihaoyi and others