"Reversing" a hook in J
Asked Answered
W

2

5

I want to put the operation which takes all the items in a list which are greater than 2 into a pointless (as in not explicitly capturing the argument in a variable) function in J. I wanted to do this by using ~ with a hook, like f =: ((> & 2) #)~ but it seems like neither that nor ((> & 2) #~) works.

My reasoning was that my function has the form (f y) g y where y is the list, f is (> & 2), and g is #. I would appreciate any help!

Whey answered 27/6, 2013 at 17:7 Comment(0)
M
7

Everything is OK except you mixed the order of the hook. It's y f (g y) so you want

 (#~ (>&2)) y
Mohler answered 27/6, 2013 at 18:55 Comment(1)
This pattern of a filter for copying is very common in J. The words that form in my mind when I see #~ appear at the left of a hook are "copy where." In this case, "copy where greater than two."Mazman
D
1

Hooks have the form f g and the interpretation, when applied to a single argument (i.e. monadically) is (unaltered input) f (g input). So, as Eelvex noted, you'd phrase this as a hook like hook =: #~ >&2 . Also, as kaledic noted, the idiom (#~ filter) is extremely common in J, so much that it's usually read as a cohesive whole: keep-items-matching-filter.*

If you wanted a point-free phrasing of the operation which looks similar, notationally, to the original noun-phrase (y > 2) # y , you might like to use the fork >&2 # ] where ] means "the unaltered input" (i.e. the identity function) or even (] # 2:) # ] or some variation.

(*) In fact, the pattern (f~ predicate) defines an entire class of idioms, like (<;.1~ frets) for cutting an array into partitions and (</.~ categories) for classifying the items of an array into buckets.

Dhar answered 8/7, 2013 at 21:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.