= #JxnPortable/docs/programmer_examples/demos/JxnFunction_Demo.jxn


#function fibonacci( n )  ! f(0) = 0; f(1) = 1; f(n) = f(n-1) + f(n-2)
   $f0 = 0; $f1 = 1  ! local variables start with '$'
   #while n -= 1  ! gt( n, 1 )
      $f2 = $f1 + $f0
      $f0 = $f1
      $f1 = $f2
      ! n -= 1
   #endwhile
   #return $f1 
#endfunction

fibonacci(1)
fibonacci(2)
fibonacci(3)
fibonacci(10)
fibonacci(90)



#function factorial( n )  ! = 1 * 2 * 3 * ... * n
   #if gt( n, 1 )
      #return factorial( n - 1 ) * n  ! recursive call
   #else
      #return 1
   #endif
#endfunction

factorial(5)
factorial(10)
factorial(20)
factorial(100)



#function gcd( a, b )  ! greatest common divisor
!  #while gt( abs b, 1E-10 abs a )  ! possible generalization of gcd
   #while b  ! ne( b, 0 )
      $tmp = b
      b = a % b
      a = $tmp
   #endwhile
   #return a
#endfunction
! gcd.setDebug 3  ! activate to show intermedeate steps

gcd( 24, 18 )
gcd( 18, 24 )
gcd( 1.75, 2.5 )  ! also works for binary fractions (generalized gcd)
gcd( 1.2, 2.1 )   ! but: finite decimal fractions may not have finite (exact) binary representation



sa = { "DEF", "abc", "XYZ", "ghi" }
Arrays.sort sa
sa
Arrays.sort( sa, @JxnF2( $this, "( s1, s2 ) -> s1.compareToIgnoreCase s2" ) )
sa



#function cot( x )
cos x / sin x
#endfunction

cot( PI/6  )

! or

cot = @JxnFunction( $this, "x -> cos x / sin x" )
cot( PI / 6 )

! test of failures:
oldDebug = $this.setAbort false
cot()
bla(1)
$this.setDebug oldDebug



coth = @JxnFunction( $this, "x -> cosh x / sinh x" )

! apply different data types:
coth 1
coth j  ! JxnComplexAlgebra
coth x  ! JxnRealArrayAlgebra
1 / $  ! should give tanh x
tanh x

slider = @JxnSliderPanel( $this )
a = slider.add( "a", 1., 0.01, 10. )
plot( x, 1 / coth a x, -tanh a x )