Incze Lajos | 7 Dec 00:58
Picon
Favicon

Write a function foo...

http://www.paulgraham.com/accgen.html:

"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."

Lang contest after the author's book excerpt (Revenge of
the Nerds, http://www.paulgraham.com/icad.html). No groovy
yet.

incze

Jochen Theodorou | 7 Dec 01:22
Picon
Gravatar

Re: Write a function foo...

Incze Lajos schrieb:
> http://www.paulgraham.com/accgen.html:
> 
> "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."

def foo(n) {
   {i->n+i}
}

i and n can be of type Number if needed.

> Lang contest after the author's book excerpt (Revenge of
> the Nerds, http://www.paulgraham.com/icad.html). No groovy
> yet.

the goal is to show how different language try to simulate Lisp ;)

bye blackdrag

Jochen Theodorou | 7 Dec 01:33
Picon
Gravatar

Re: Write a function foo...

Jochen Theodorou schrieb:

> Incze Lajos schrieb:
> 
>> http://www.paulgraham.com/accgen.html:
>>
>> "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."
> 
> 
> def foo(n) {
>   {i->n+i}
> }

made a mistake here, the above returns n plus i, not n incremented by i. 
So the version is:

  def foo(n) {
    {i->n+=i}
  }

examples in other languages can be found here: 
http://www.paulgraham.com/accgen.html

bye blackdrag

Jeremy Rayner | 7 Dec 09:39
Picon
Gravatar

Re: Write a function foo...

I also came up with

def foo(n){
  {i-> n+=i}
}

...but I thought I'd explain the process a bit, just
to expose the magic of syntax sugar in groovy...

The Java example was
----
public static Inttoint foo(final int n) {
	return new Inttoint() {
		int s = n;
		public int call(int i) {
			s = s + i;
			return s;
		}
	};
}
----
refactorings into groovy
i) This rather verbose code is returning an Inttoint object,
which has one method call(int i), this callback is a perfect
candidate for replacement with Closure as the return type.

ii) The intermediate instance variable s is not needed in
groovy as with true closures the variable n will be lexically
bound, so we can refer to n directly in the method body of call(int i){...

(Continue reading)


Gmane