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


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

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



#function factorial( n )  ! = 1 * 2 * 3 * ... * n
   $i = 1; $result = 1  ! local variables
   #while le( $i, n )
      $result *= $i
      $i += 1
   #endwhile
   #return $result
#endfunction

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



#function gcd( a, b )  ! greatest common divisor
!  a + " " + b
!  #if gt( abs b, 1E-10 abs a )  ! possible generalization of gcd
   #if ne( b, 0 )
      #return gcd( b, a % b )  ! recursive call
   #else
      #return a
   #endif
#endfunction
! gcd.setDebug 1

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.setDebug 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 )