Hi all -

While doing a little piece on computing Fibonacci numbers and the 
Golden ratio, I came across this behaviour of recursive functions 
which I do not yet understand:

(A)
Defining a simple range as
    r:=. 2 + i.7
2 3 4 5 6 7 8
I have been able to print e.g. a small table of sines
    > r,. sin r
2  0.909297427
3  0.141120008
4 _0.756802495
5 _0.958924275
6 _0.279415498
7  0.656986599
8  0.989358247

(B)
Playing around with the factorial I found that

(B1) using this definition (from: Burke/Reiter, Brief Reference)
    fac=: 3 : 'if. y <: 1 do. 1 else. y * fac y - 1 end.'
I will get
    fac 5
120
alright, but
    > r,. fac r
2 2
3 3
4 4
5 5
6 6
7 7
8 8
which seems strange (at least to me).

(B2) using this slightly more elaborate definition
    fac=: 3 : 0
    n=. y
    select. n
     case. 0 do. f=. 1
     case. 1 do. f=. 1
     case.   do. f=. n * fac (n-1)
    end.
    f
    )
I will get
    fac 5
120
as above, but
    > r,. fac r
|stack error: fac
|   f=.n*    fac(n-1)

(C)
Something similar happens with ((sorry for probable too may parentheses))
    fib=: 3 : 0
    n=. y
    select. n
     case. 0 do. f=. 0
     case. 1 do. f=. 1
     case.   do. f=. (fib (n-1)) + (fib (n-2))
   end.
   f
   )
    fib 13
233
computes alright, but this throws an error
    > r,. fib r
|stack error: fib
|   f=.(fib(n-1))+(    fib(n-2))

Could anybody shed some light on this..? Thanks, M.



---
avast! Antivirus: Outbound message clean.
Virus Database (VPS): 090815-0, 15.08.2009
Tested on: 16.08.2009 13:14:34
avast! - copyright (c) 1988-2009 ALWIL Software.
http://www.avast.com



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

Reply via email to