Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write 4 : 'x&{.&.;: y' tacitly

Conor Hoekstra recently solved a Leetcode problem in APL https://youtu.be/QtvvQ7MdwKY The problem is to take the first x words from a character string y

In J, using &. (Under) and ;: (Words) I can come up with a nice explicit one liner

solve =. 4 : 'x&{.&.;: y'         NB. Box words in y -> take first x-> unbox words in result while retaining spaces between
   s=. 'Hello how are you Contestant'
   4 solve s
Hello how are you

The trouble I am having is finding the tacit version that still includes &., mainly because I believe x needs to be bound to {. during the creation of the verb. This is also an example where the magic 13 : conversion is not helpful

   13 : 'x&{.&.;: y'
4 : 'x&{.&.;: y'

I can solve it tacitly by using ;:^:_1 to create the inverse of ;:

   solve2=. (;:^:_1)@:({. ;:)
   4 solve2 s
Hello how are you

But that is not nearly as pretty as the tacit version of 4 : 'x&{.&.;: y' could be.
Anyone have a pretty tacit solution for 4 : 'x&{.&.;: y'?

like image 859
bob Avatar asked Dec 18 '22 11:12

bob


2 Answers

With semiduals (introduced with J902 or J903?) you can write 4 {.&.(a:`;:) s. Then ;: gets only applied to the right argument, while still doing the inverse later. u&.(f`a:) would apply f only on the left argument.

like image 145
xash Avatar answered Dec 28 '22 16:12

xash


mainly because I believe x needs to be bound to {. during the creation of the verb.

If creating a verb with an input is the key, shouldn't you use an adverb?

   solve =: 1 : 'm&{.&.;:'
   4 solve
4&{.&.;:
   (4 solve ,: 2 solve) 'Hello how are you Contestant'
Hello how are you
Hello how        

solve itself isn't tacit (or a verb), but 4 solve is tacit verb.

like image 36
Julian Fondren Avatar answered Dec 28 '22 17:12

Julian Fondren