-
Notifications
You must be signed in to change notification settings - Fork 19
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
Setter -> Traversal #32
Comments
I'm not sure I understand what you're trying to say. I don't get how side-effects could unify setters and traversals. If you want a traversal that focuses parts of a string that are matched by a regex, then you'd write it like this: import re
from lenses import lens
def regex_traversal(pattern, flags=0):
def folder(state):
for match in re.finditer(pattern, state, flags=flags):
yield match.group(0)
def builder(state, values):
iterator = iter(values)
return re.sub(pattern, lambda _: next(iterator), state, flags=flags)
return lens.Traversal(folder, builder)
state = "First thou pullest the Holy Pin"
state &= regex_traversal("\w+") + "!"
print(state) # "First! thou! pullest! the! Holy! Pin!" If there's a better way to write this I'd like to know. |
builder should take a generator of values instead of a list, of course. For better streaming:
I spent a few days there trying to stream Traversal.func correctly for an arbitrary Applicative ^^. |
How useful would it be to have a general convenience method for this? Haskell-style setter functions |
Python's nonlocal state side effects give every setter traversal powers. You should unify them or have a utility to convert them.
I say this because using
re.sub
(which allows a function argument) for a traversal is turning out much harder than thelambda regex: Setter(lambda f s: re.sub(regex, f, s))
it should be.The text was updated successfully, but these errors were encountered: