4

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'?

3 Answers 3

8

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.

1
  • 1
    Wow, I did not know this. Every time I turn around this language surprises me and I have been playing with it for 20 years! Off to play some more. Thank you xash
    – bob
    Apr 7, 2021 at 22:24
3

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.

2
  • Yes, thank you Julian. I was not thinking of adverbs as a valid tacit solution. Great answer.
    – bob
    Apr 6, 2021 at 6:29
  • 1
    ...and _3 grab_words 'are you ready to go' if you want to get words from end of string. Apr 6, 2021 at 10:04
1

I don't think you can write this as a tacit verb, but it's easy to do as a tacit adverb: ]:&{.&.;:.

1
  • 1
    Yes, you are quite correct, although at the time that the question was asked, tacit modifiers had not been reintroduced to the language.
    – bob
    May 30, 2022 at 16:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.