3 ms·
This is a pretty neat pattern. One nice bonus is that the code invoking the closure has a chance to do work after the closure. This lets you do nice "scoped" be
by munificent 13y ago
This is a pretty neat pattern. One nice bonus is that the code invoking the closure has a chance to do work after the closure. This lets you do nice "scoped" behavior automatically. For example, in his Ruby code:
data_source.person(id) do |person|
person.phone_number = phone_number
data_source.update_person person
end
I would take that `update_person` call and have the `person(id)` method do that implicitly:
data_source.person(id) do |person|
person.phone_number = phone_number
end
(I'd likely optimize for the case where the person wasn't actually modified too.) This way, the caller doesn't have to remember to explicitly update the person.
Another way to look at this pattern is as a poor-man's pattern match. For example, using the pattern-matching syntax of my language[1], you could do:
match dataSource person(id)
case person is Person then
person phoneNumber = phoneNumber
dataSource updatePerson(person)
end
Granted, that's more verbose here, but it lets you have other cases if that makes sense for your problem. Magpie has blocks too, so a literal translation would be:
dataSource person(id) as person do
person phoneNumber = phoneNumber
end
For very short blocks, you can use an implicit parameter name similar to Scala:
dataSource person(id) do _ phoneNumber = phoneNumber
The `do` notation is just syntactic sugar for passing a function as the last argument, so you can also do:
dataSource person(id, fn(person) person phoneNumber = phoneNumber)
How did I get derailed talking about Magpie?
[1]: http://magpie-lang.org/ http://magpie-lang.org/