Here is a J way to "Write a function foo that takes a number n and returns a function that takes a number i, and returns n incremented by i."

   foo =: 1 : 'm + y'

   f =: 7 foo

   f 3
10
   f 13
20

   NB. Also

   (7 foo) 3
10

   7 foo 3
10

The function produced by 7 foo takes an argument i and returns 7 incremented by i. Whether foo is a function depends on how general your definition of "function" is.

Kip Murray


bill lam wrote:
On Sun, 26 Apr 2009, Alan K. Stebbens wrote:
A programming comparison on the web had this question:

The problem: Write a function foo that takes a number n and returns a function that takes a number i, and returns n incremented by i.
The concept of embedding context within a function definition is called a "closure". So, I guess I'm asking is if there is a "standard" way to accomplish closures in J?
  bar
┌─┬─┬───┐
│3│:│7+y│
└─┴─┴───┘
  bar 3
10

I think that your `bar' does not satisfy the requirement. When it is
called again, it should add 10 (not 7) to the number.  This closure
had been discussed on this list and appeared in jwiki, iirc.

J is not good in this problem or this is not a good problem for J. :-)

----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm

Reply via email to