4 ms·
Some commenters are pointing out that this is similar to "with" in Python.[0] At first glance - and using the example given of reading from a file - that may be
by ecdavis 11y ago
Some commenters are pointing out that this is similar to "with" in Python.[0] At first glance - and using the example given of reading from a file - that may be true, but consider the final example given in the article. The Pythonic way to calculate the magnitude is something like:
math.sqrt(sum((i**2 for i in numbers)))
Using "with" to calculate a magnitude would be tortuous at best and it certainly wouldn't result in idiomatic code.
The point of the article is to illustrate the idiom: perform operation A, then operation B, then the inverse of operation A. "with open(foo)" or "using (foo)" implements that idiom in certain, specific cases, but not in the general case which seems to be what J implements.
[0] Or "using" in C#, for that matter.
- matchu 11y agoI think the issue here is that the article is talking about two things: a common resource management idiom, and the cool fact that `under(f, g) = f^1 * g * f` implements it. `with` implements this idiom just fine, too, but `under` is a more general solution that can solve even more problems, if you're willing to be a bit more careful about `f` and `g`. In the Read/Open case, for example, it looks like Read must return both the read result and the file handle, and Open^-1 must take the read result as input and forward it back out as output. Feasible, but unintuitive for the implementers. If we were actually implementing this resource management idiom, I'm not sure we would use `under`, even though we could. If we want to write `f`, `f^-1`, and `g` with the more natural `with` semantics, it's clearer to define our own metafunction from scratch: `with(f, g)(x) = (g(f_result), f^-1(f_result)) where f_result = f(x)`. edit: The follow-up post actually touches on how Read/Open really isn't a great example of `under`. Interesting. http://prog21.dadgum.com/122.html http://prog21.dadgum.com/122.html
- Rangi42 11y agoIn J, you can square a vector and get a vector of the squared entries. So "sum under square" really is doing "sqrt(sum(square(vector)))", and more generally "(a under b) x" does "b^-1(a(b(x)))".
- matchu 11y agoMm, I thought that might be what's up, but had no clue how J actually works xD Thanks! Even without the mapping wrinkle, though, this is definitely a deviation from the examples the article provides: instead of unsquaring the vector we initially squared, we unsquare the sum.
- deleted 11y ago[deleted]
- JadeNB 11y ago> I think the issue here is that the article is talking about two things: a common resource management idiom, and the cool fact that `under(f, g) = f^1 * g * f` implements it. I think that your pseudo-code for `under` should start with `f^(-1)` (as in the fourth paragraph); probably `f^1` is just a typo.
- matchu 11y agoWhoops, yeah. Edit button is gone now, boooo.