Talk:Anonymous recursion: Difference between revisions

(J Example control structure)
Line 116:
 
::Since the J solution acts like an identity when called with negative arguments the check for negative numbers can be performed after the fibonacci function is called, signalling a domain error if the result is negative: <lang J>fibN =: 3 : '[:^:(0&>) (-&2 +&$: -&1)^:(1&<) M. y'"0</lang> Alternatively using a control structure: <lang J>(3 : 'if. y<0 do. <''negative argument'' else. <(-&2 +&$: -&1)^:(1&<) M. y end.'"0)</lang> --[[User:Zeotrope|Zeotrope]] 19:48, 8 January 2011 (UTC)
 
== Recursion implies a function ==
 
I am the author of the examples for Ruby and for UNIX Shell which create and hide a recursive function.
 
I believe that the use of recursion implies the existence of a function. To have recursion, one must call a thing, and this thing must return; therefore this thing is a function. The task is to hide the extra function so that it does not pollute the namespace nor become available to other functions. JavaScript 'arguments.callee' and PicoLisp 'recurse' only hide a function. I show this by porting them to Ruby. --[[User:Kernigh|Kernigh]] 22:20, 8 January 2011 (UTC)
 
<lang ruby># a function almost like JavaScript
class Function
def initialize(*params, &block)
@params = Struct.new(:callee, *params)
@block = block # ___ hiding a function! ___
end
 
def call(*args)
@block[@params.new(self, *args)]
end
 
alias [] call
end
 
def fibo(n)
if n < 0
raise "Argument cannot be negative"
else
return (Function.new(:n) { |arguments|
if arguments.n < 2
next 1
else
next (arguments.callee[arguments.n-1] +
arguments.callee[arguments.n-2])
end
})[n]
end
end</lang>
 
<lang ruby># recur/recurse almost like PicoLisp
def recur(*args, &block)
old_recurse = $recurse
begin
$recurse = block # ___ hiding a function! ___
$recurse[*args]
ensure
$recurse = old_recurse
end
end
 
def fib(n)
if n < 0
raise "Illegal argument #{n}"
end
recur(n) { |n|
if 2 > n
1
else
$recurse[n.pred] + $recurse[n - 2]
end
}
end</lang>
Anonymous user