Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter a list in J?

Tags:

I'm currently learning the fascinating J programming language, but one thing I have not been able to figure out is how to filter a list.

Suppose I have the arbitrary list 3 2 2 7 7 2 9 and I want to remove the 2s but leave everything else unchanged, i.e., my result would be 3 7 7 9. How on earth do I do this?

like image 784
Gregory Higley Avatar asked May 19 '10 10:05

Gregory Higley


1 Answers

The short answer

   2 (~: # ]) 3 2 2 7 7 2 9 3 7 7 9 


The long answer

I have the answer for you, but before you should get familiar with some details. Here we go.

Monads, dyads

There are two types of verbs in J: monads and dyads. The former accept only one parameter, the latter accept two parameters.

For example passing a sole argument to a monadic verb #, called tally, counts the number of elements in the list:

   # 3 2 2 7 7 2 9 7 

A verb #, which accepts two arguments (left and right), is called copy, it is dyadic and is used to copy elements from the right list as many times as specified by the respective elements in the left list (there may be a sole element in the list also):

   0 0 0 3 0 0 0 # 3 2 2 7 7 2 9 7 7 7 

Fork

There's a notion of fork in J, which is a series of 3 verbs applied to their arguments, dyadically or monadically.

Here's the diagram of a kind of fork I used in the first snippet:

 x (F G H) y        G     /   \    F     H   / \   / \  x   y x   y 

It describes the order in which verbs are applied to their arguments. Thus these applications occur:

   2 ~: 3 2 2 7 7 2 9 1 0 0 1 1 0 1 

The ~: (not equal) is dyadic in this example and results in a list of boolean values which are true when an argument doesn't equal 2. This was the F application according to diagram.

The next application is H:

   2 ] 3 2 2 7 7 2 9 3 2 2 7 7 2 9 

] (identity) can be a monad or a dyad, but it always returns the right argument passed to a verb (there's an opposite verb, [ which returns.. Yes, the left argument! :)

So far, so good. F and H after application returned these values accordingly:

1 0 0 1 1 0 1 3 2 2 7 7 2 9 

The only step to perform is the G verb application.

As I noted earlier, the verb #, which is dyadic (accepts two arguments), allows us to duplicate the items from the right argument as many times as specified in the respective positions in the left argument. Hence:

   1 0 0 1 1 0 1 # 3 2 2 7 7 2 9 3 7 7 9 

We've just got the list filtered out of 2s.

Reference

Slightly different kind of fork, hook and other primitves (including abovementioned ones) are described in these two documents:

  • A Brief J Reference (175 KiB)
  • Easy-J. An Introduction to the World's most Remarkable Programming Language (302 KiB)

Other useful sources of information are the Jsoftware site with their wiki and a few mail list archives in internets.

like image 165
15 revs Avatar answered Oct 22 '22 21:10

15 revs