import "dome" for Window
import "graphics" for Canvas, Color, ImageData
import "math" for Math
import "./check" for Check

var MaxBrightness = 255

class Canny {
    construct new(inFile, outFile) {
        Window.title = "Canny edge detection"
        var image1 = ImageData.loadFromFile(inFile)
        var w = image1.width
        var h = image1.height
        Window.resize(w * 2 + 20, h)
        Canvas.resize(w * 2 + 20, h)
        var image2 = ImageData.create(outFile, w, h)
        var pixels = List.filled(w * h, 0)
        var ix = 0
        // convert image1 to gray scale as a list of pixels
        for (y in 0...h) {
            for (x in 0...w) {
                var c1 = image1.pget(x, y)
                var lumin = (0.2126 * c1.r + 0.7152 * c1.g + 0.0722 * c1.b).floor
                pixels[ix] = lumin
                ix = ix + 1
            }
        }

        // find edges
        var data = cannyEdgeDetection(pixels, w, h, 45, 50, 1)

        // write to image2
        ix = 0
        for (y in 0...h) {
            for (x in 0...w) {
                var d = data[ix]
                var c = Color.rgb(d, d, d)
                image2.pset(x, y, c)
                ix = ix + 1
            }
        }

        // display the two images side by side
        image1.draw(0, 0)
        image2.draw(w + 20, 0)

        // save image2 to outFile
        image2.saveToFile(outFile)
    }

    init() {}

    // If normalize is true, map pixels to range 0..MaxBrightness
    convolution(input, output, kernel, nx, ny, kn, normalize) {
        Check.ok((kn % 2) == 1)
        Check.ok(nx > kn && ny > kn)
        var khalf = (kn / 2).floor
        var min = Num.largest
        var max = -min
        if (normalize) {
            for (m in khalf...nx-khalf) {
                for (n in khalf...ny-khalf) {
                    var pixel = 0
                    var c = 0
                    for (j in -khalf..khalf) {
                        for (i in -khalf..khalf) {
                            pixel = pixel + input[(n-j)*nx + m - i] * kernel[c]
                            c = c + 1
                        }
                    }
                    if (pixel < min) min = pixel
                    if (pixel > max) max = pixel
                }
            }
        }

        for (m in khalf...nx-khalf) {
            for (n in khalf...ny-khalf) {
                var pixel = 0
                var c = 0
                for (j in -khalf..khalf) {
                    for (i in -khalf..khalf) {
                        pixel = pixel + input[(n-j)*nx + m - i] * kernel[c]
                        c = c + 1
                    }
                }
                if (normalize) pixel = MaxBrightness * (pixel - min) / (max - min)
                output[n * nx + m] = pixel.truncate
            }
        }
    }

    gaussianFilter(input, output, nx, ny, sigma) {
        var n = 2 * (2 * sigma).truncate + 3
        var mean = (n / 2).floor
        var kernel = List.filled(n * n, 0)
        System.print("Gaussian filter: kernel size = %(n), sigma = %(sigma)")
        var c = 0
        for (i in 0...n) {
            for (j in 0...n) {
                var t = (-0.5 * (((i - mean) / sigma).pow(2) + ((j - mean) / sigma).pow(2))).exp
                kernel[c] = t / (2 * Num.pi * sigma * sigma)
                c = c + 1
            }
        }
        convolution(input, output, kernel, nx, ny, n, true)
    }

    // Returns the square root of 'x' squared + 'y' squared.
    hypot(x, y) { (x*x + y*y).sqrt }

    cannyEdgeDetection(input, nx, ny, tmin, tmax, sigma) {
        var output = List.filled(input.count, 0)
        gaussianFilter(input, output, nx, ny, sigma)
        var Gx = [-1, 0, 1, -2, 0, 2, -1, 0, 1]
        var afterGx = List.filled(input.count, 0)
        convolution(output, afterGx, Gx, nx, ny, 3, false)
        var Gy = [1, 2, 1, 0, 0, 0, -1, -2, -1]
        var afterGy = List.filled(input.count, 0)
        convolution(output, afterGy, Gy, nx, ny, 3, false)
        var G = List.filled(input.count, 0)
        for (i in 1..nx-2) {
            for (j in 1..ny-2) {
                var c = i + nx * j
                G[c] = hypot(afterGx[c], afterGy[c]).floor
            }
        }

        // non-maximum suppression: straightforward implementation
        var nms = List.filled(input.count, 0)
        for (i in 1..nx-2) {
            for (j in 1..ny-2) {
                var c = i + nx * j
                var nn = c - nx
                var ss = c + nx
                var ww = c + 1
                var ee = c - 1
                var nw = nn + 1
                var ne = nn - 1
                var sw = ss + 1
                var se = ss - 1
                var temp = Math.atan(afterGy[c], afterGx[c]) + Num.pi
                var dir = (temp % Num.pi) / Num.pi * 8
                if (((dir <= 1 || dir > 7) && G[c] > G[ee] && G[c] > G[ww]) ||   // O°
                    ((dir > 1 && dir <= 3) && G[c] > G[nw] && G[c] > G[se]) ||   // 45°
                    ((dir > 3 && dir <= 5) && G[c] > G[nn] && G[c] > G[ss]) ||   // 90°
                    ((dir > 5 && dir <= 7) && G[c] > G[ne] && G[c] > G[sw])) {   // 135°
                    nms[c] = G[c]
                } else {
                    nms[c] = 0
                }
            }
        }

        // tracing edges with hysteresis: non-recursive implementation
        var edges = List.filled((input.count/2).floor, 0)
        for (i in 0...output.count) output[i] = 0
        var c = 1
        for (j in 1..ny-2) {
            for (i in 1..nx-2) {
                if (nms[c] >= tmax && output[c] == 0) {
                    // trace edges
                    output[c] = MaxBrightness
                    var nedges = 1
                    edges[0] = c
                    while (true) {
                        nedges = nedges - 1
                        var t = edges[nedges]
                        var nbs = [     // neighbors
                           t - nx,      // nn
                           t + nx,      // ss
                           t + 1,       // ww
                           t - 1,       // ee
                           t - nx + 1,  // nw
                           t - nx - 1,  // ne
                           t + nx + 1,  // sw
                           t + nx - 1   // se
                        ]
                        for (n in nbs) {
                            if (nms[n] >= tmin && output[n] == 0) {
                                output[n] = MaxBrightness
                                edges[nedges] = n
                                nedges = nedges + 1
                            }
                        }
                        if (nedges == 0) break
                    }
                }
                c = c + 1
            }
        }
        return output
    }

    update() {}

    draw(alpha) {}
}
var Game = Canny.new("Valve_original.png", "Valve_monchrome_canny.png")


with Ada.Text_IO;  use Ada.Text_IO;

procedure Test_Catalan is
   function Catalan (N : Natural) return Natural is
      Result : Positive := 1;
   begin
      for I in 1..N loop
         Result := Result * 2 * (2 * I - 1) / (I + 1);
      end loop;
      return Result;
   end Catalan;
begin
   for N in 0..15 loop
      Put_Line (Integer'Image (N) & " =" & Integer'Image (Catalan (N)));
   end loop;
end Test_Catalan;


# calculate the first few catalan numbers, using LONG INT values        #
# (64-bit quantities in Algol 68G which can handle up to C23)           #

# returns n!/k!                                                         #
PROC factorial over factorial = ( INT n, k )LONG INT:
     IF      k > n THEN 0
     ELIF    k = n THEN 1
     ELSE #  k < n #
         LONG INT f := 1;
         FOR i FROM k + 1 TO n DO f *:= i OD;
         f
     FI # factorial over factorial # ;

# returns n!                                                             #
PROC factorial = ( INT n )LONG INT:
     BEGIN
         LONG INT f := 1;
         FOR i FROM 2 TO n DO f *:= i OD;
         f
     END # factorial # ;

# returnss the nth Catalan number using binomial coefficeients            #
# uses the factorial over factorial procedure for a slight optimisation   #
# note:     Cn = 1/(n+1)(2n n)                                            #
#              = (2n)!/((n+1)!n!)                                         #
#              = factorial over factorial( 2n, n+1 )/n!                   #
PROC catalan = ( INT n )LONG INT: IF n < 2 THEN 1 ELSE factorial over factorial( n + n, n + 1 ) OVER factorial( n ) FI;

# show the first few catalan numbers                                      #
FOR i FROM 0 TO 15 DO
    print( ( whole( i, -2 ), ": ", whole( catalan( i ), 0 ), newline ) )
OD


cartmulti := proc ()
 local m, v;
 if [] in {args} then
 return [];
 else
m := Iterator:-CartesianProduct(args);
 for v in m do
 printf("%{}a\n", v);
 end do;
 end if;
 end proc;


cartesianProduct[args__] := Flatten[Outer[List, args], Length[{args}] - 1]


! type declaration
type my_type
 contains
procedure, pass :: method1
procedure, pass, pointer :: method2
end type my_type

! declare object of type my_type
type(my_type) :: mytype_object

!static call
 call mytype_object%method1() ! call method1 defined as subroutine
!instance?
 mytype_object%method2() ! call method2 defined as function


' FB 1.05.0 Win64

Type MyType
  Public:
    Declare Sub InstanceMethod(s As String)
    Declare Static Sub StaticMethod(s As String)
  Private:
    dummy_ As Integer ' types cannot be empty in FB
End Type

Sub MyType.InstanceMethod(s As String)
  Print s
End Sub

Static Sub MyType.StaticMethod(s As String)
  Print s
End Sub

Dim t As MyType
t.InstanceMethod("Hello world!")
MyType.Staticmethod("Hello static world!")
Print
Print "Press any key to quit the program"
Sleep


type Foo int // some custom type

// method on the type itself; can be called on that type or its pointer
func (self Foo) ValueMethod(x int) { }

// method on the pointer to the type; can be called on pointers
func (self *Foo) PointerMethod(x int) { }

var myValue Foo
var myPointer *Foo = new(Foo)

// Calling value method on value
myValue.ValueMethod(someParameter)
// Calling pointer method on pointer
myPointer.PointerMethod(someParameter)

// Value methods can always be called on pointers
// equivalent to (*myPointer).ValueMethod(someParameter)
myPointer.ValueMethod(someParameter)

// In a special case, pointer methods can be called on values that are addressable (i.e. lvalues)
// equivalent to (&myValue).PointerMethod(someParameter)
myValue.PointerMethod(someParameter)

// You can get the method out of the type as a function, and then explicitly call it on the object
Foo.ValueMethod(myValue, someParameter)
(*Foo).PointerMethod(myPointer, someParameter)
(*Foo).ValueMethod(myPointer, someParameter)


procedure main()

   bar := foo()  # create instance
   bar.m2()      # call method m2 with self=bar, an implicit first parameter

   foo_m1( , "param1", "param2")  # equivalent of static class method, first (self) parameter is null
end

class foo(cp1,cp2)
   method m1(m1p1,m1p2)
      local ml1
      static ms1
      ml1 := m1p1
      # do something
      return
   end
   method m2(m2p1)
      # do something else
      return
   end
initially
   L := [cp1]
end


// Rosetta Code problem: http://rosettacode.org/wiki/Canny_edge_detector
// Adapted from Phix to Yabasic by Galileo, 01/2022

import ReadFromPPM2

MaxBrightness = 255

readPPM("Valve.ppm")
print "Be patient, please ..."

width = peek("winwidth")
height = peek("winheight")
dim pixels(width, height), C_E_D(3, 3)

data -1, -1, -1, -1,  8, -1, -1, -1, -1
for i = 0 to 2
    for j = 0 to 2
        read C_E_D(i, j)
    next
next

// convert image to gray scale
for y = 1 to height
    for x = 1 to width
        c$ = right$(getbit$(x, y, x, y), 6)
        r = dec(left$(c$, 2))
        g = dec(mid$(c$, 3, 2))
        b = dec(right$(c$, 2))
        lumin = floor(0.2126 * r + 0.7152 * g + 0.0722 * b)
        pixels(x, y) = lumin
    next
next

dim new_image(width, height)

divisor = 1

// apply an edge detection filter

for y = 2 to height-2
    for x = 2 to width-2
        newrgb = 0
        for i = -1 to 1
            for j = -1 to 1
                newrgb = newrgb + C_E_D(i+1, j+1) * pixels(x+i, y+j)
            next
            new_image(x, y) = max(min(newrgb / divisor,255),0)
        next
    next
next

// show result

for x = 1 to width
    for y = 1 to height
        c = new_image(x, y)
        color c, c, c
        dot x, y
    next
next


begin
    % print the catalan numbers up to C15 %
    integer Cprev;
    Cprev := 1; % C0 %
    write(     s_w := 0, i_w := 3, 0, ": ", i_w := 9, Cprev );
    for n := 1 until 15 do begin
        Cprev := round( ( ( ( 4 * n ) - 2 ) / ( n + 1 ) ) * Cprev );
        write( s_w := 0, i_w := 3, n, ": ", i_w := 9, Cprev );
    end for_n
end.


catalan: function [n][
	if? n=0 -> 1
	else 	-> div (catalan n-1) * (4*n)-2 n+1
]

loop 0..15 [i][
	print [
		pad.right to :string i 5
		pad.left to :string catalan i 20
	]
]


MODULE CartesianProduct;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;

PROCEDURE WriteInt(a : INTEGER);
VAR buf : ARRAY[0..9] OF CHAR;
BEGIN
    FormatString("%i", buf, a);
    WriteString(buf)
END WriteInt;

PROCEDURE Cartesian(a,b : ARRAY OF INTEGER);
VAR i,j : CARDINAL;
BEGIN
    WriteString("[");
    FOR i:=0 TO HIGH(a) DO
        FOR j:=0 TO HIGH(b) DO
            IF (i>0) OR (j>0) THEN
                WriteString(",");
            END;
            WriteString("[");
            WriteInt(a[i]);
            WriteString(",");
            WriteInt(b[j]);
            WriteString("]")
        END
    END;
    WriteString("]");
    WriteLn
END Cartesian;

TYPE
    AP = ARRAY[0..1] OF INTEGER;
    E = ARRAY[0..0] OF INTEGER;
VAR
    a,b : AP;
BEGIN
    a := AP{1,2};
    b := AP{3,4};
    Cartesian(a,b);

    a := AP{3,4};
    b := AP{1,2};
    Cartesian(a,b);

    (* If there is a way to create an empty array, I do not know of it *)

    ReadChar
END CartesianProduct.


data Obj = Obj { field :: Int, method :: Int -> Int }

-- smart constructor
mkAdder :: Int -> Obj
mkAdder x = Obj x (+x)

-- adding method from a type class
instanse Show Obj where
  show o = "Obj " ++ show (field o)


ClassWithStaticMethod.staticMethodName(argument1, argument2);//for methods with no arguments, use empty parentheses


class MyClass {
    fun instanceMethod(s: String) = println(s)

    companion object {
        fun staticMethod(s: String) = println(s)
    }
}

fun main(args: Array<String>) {
    val mc = MyClass()
    mc.instanceMethod("Hello instance world!")
    MyClass.staticMethod("Hello static world!")
}


Loop 15
   out .= "`n" Catalan(A_Index)
Msgbox % clipboard := SubStr(out, 2)
catalan( n ) {
; By [VxE]. Returns ((2n)! / ((n + 1)! * n!)) if 0 <= N <= 22 (higher than 22 results in overflow)
If ( n < 3 ) ; values less than 3 are handled specially
   Return n < 0 ? "" : n = 0 ? 1 : n

i := 1 ; initialize the accumulator to 1

Loop % n - 1 >> 1 ; build the numerator by multiplying odd values between 2N and N+1
   i *= 1 + ( n - A_Index << 1 )

i <<= ( n - 2 >> 1 ) ; multiply the numerator by powers of 2 according to N

Loop % n - 3 >> 1 ; finish up by (integer) dividing by each of the non-cancelling factors
   i //= A_Index + 2

Return i
}


# syntax: GAWK -f CATALAN_NUMBERS.AWK
BEGIN {
    for (i=0; i<=15; i++) {
      printf("%2d %10d\n",i,catalan(i))
    }
    exit(0)
}
function catalan(n,  ans) {
    if (n == 0) {
      ans = 1
    }
    else {
      ans = ((2*(2*n-1))/(n+1))*catalan(n-1)
    }
    return(ans)
}


iterator product[T1, T2](a: openArray[T1]; b: openArray[T2]): tuple[a: T1, b: T2] =
  # Yield the element of the cartesian product of "a" and "b".
  # Yield tuples rather than arrays as it allows T1 and T2 to be different.

  for x in a:
    for y in b:
      yield (x, y)

#———————————————————————————————————————————————————————————————————————————————————————————————————

when isMainModule:

  from seqUtils import toSeq
  import strformat
  from strutils import addSep

  #-------------------------------------------------------------------------------------------------

  proc `$`[T1, T2](t: tuple[a: T1, b: T2]): string =
    ## Overloading of `$` to display a tuple without the field names.
    &"({t.a}, {t.b})"

  proc `$$`[T](s: seq[T]): string =
    ## New operator to display a sequence using mathematical set notation.
    result = "{"
    for item in s:
      result.addSep(", ", 1)
      result.add($item)
    result.add('}')

#-------------------------------------------------------------------------------------------------

  const Empty = newSeq[int]()   # Empty list of "int".

  for (a, b) in [(@[1, 2], @[3, 4]),
                 (@[3, 4], @[1, 2]),
                 (@[1, 2],  Empty ),
                 ( Empty,  @[1, 2])]:

    echo &"{$$a} x {$$b} = {$$toSeq(product(a, b))}"


myObject someMethod (arg1, arg2, arg3).
MyClass someMethod (arg1, arg2, arg3).


(defmodule aquarium
 (export all))

(defun fish-class (species)
  "
  This is the constructor that will be used most often, only requiring that
  one pass a 'species' string.

  When the children are not defined, simply use an empty list.
  "
  (fish-class species ()))

(defun fish-class (species children)
  "
  This contructor is mostly useful as a way of abstracting out the id
  generation from the larger constructor. Nothing else uses fish-class/2
  besides fish-class/1, so it's not strictly necessary.

  When the id isn't know, generate one.
  "
  (let* (((binary (id (size 128))) (: crypto rand_bytes 16))
         (formatted-id (car
                         (: io_lib format
                           '"~32.16.0b" (list id)))))
    (fish-class species children formatted-id)))

(defun fish-class (species children id)
  "
  This is the constructor used internally, once the children and fish id are
  known.
  "
  (let ((move-verb '"swam"))
    (lambda (method-name)
      (case method-name
        ('id
          (lambda (self) id))
        ('species
          (lambda (self) species))
        ('children
          (lambda (self) children))
        ('info
          (lambda (self)
            (: io format
              '"id: ~p~nspecies: ~p~nchildren: ~p~n"
              (list (get-id self)
                    (get-species self)
                    (get-children self)))))
        ('move
          (lambda (self distance)
            (: io format
              '"The ~s ~s ~p feet!~n"
              (list species move-verb distance))))
        ('reproduce
          (lambda (self)
            (let* ((child (fish-class species))
                   (child-id (get-id child))
                   (children-ids (: lists append
                                   (list children (list child-id))))
                   (parent-id (get-id self))
                   (parent (fish-class species children-ids parent-id)))
              (list parent child))))
        ('children-count
          (lambda (self)
            (: erlang length children)))))))

(defun get-method (object method-name)
  "
  This is a generic function, used to call into the given object (class
  instance).
  "
  (funcall object method-name))

; define object methods
(defun get-id (object)
  (funcall (get-method object 'id) object))

(defun get-species (object)
  (funcall (get-method object 'species) object))

(defun get-info (object)
  (funcall (get-method object 'info) object))

(defun move (object distance)
  (funcall (get-method object 'move) object distance))

(defun reproduce (object)
  (funcall (get-method object 'reproduce) object))

(defun get-children (object)
  (funcall (get-method object 'children) object))

(defun get-children-count (object)
  (funcall (get-method object 'children-count) object))


DECLARE FUNCTION catalan (n AS INTEGER) AS SINGLE

REDIM SHARED results(0) AS SINGLE

FOR x% = 1 TO 15
    PRINT x%, catalan (x%)
NEXT

FUNCTION catalan (n AS INTEGER) AS SINGLE
    IF UBOUND(results) < n THEN REDIM PRESERVE results(n)

    IF 0 = n THEN
    	results(0) = 1
    ELSE
    	results(n) = ((2 * ((2 * n) - 1)) / (n + 1)) * catalan(n - 1)
    END IF
    catalan = results(n)
END FUNCTION


function factorial(n)
    if n = 0 then return 1
    return n * factorial(n - 1)
end function

function catalan1(n)
    prod = 1
    for i = n + 2 to 2 * n
        prod *= i
    next i
    return int(prod / factorial(n))
end function

function catalan2(n)
    if n = 0 then return 1
    sum = 0
    for i = 0 to n - 1
        sum += catalan2(i) * catalan2(n - 1 - i)
    next i
    return sum
end function

function catalan3(n)
    if n = 0 then return 1
    return catalan3(n - 1) * 2 * (2 * n - 1) \ (n + 1)
end function

print "n", "First", "Second", "Third"
print "-", "-----", "------", "-----"
print
for i = 0 to 15
    print i,  catalan1(i), catalan2(i), catalan3(i)
next i


-- call static method
script("MyClass").foo()

-- call instance method
obj = script("MyClass").new()
obj.foo()


% avoid infinite metaclass regression by
% making the metaclass an instance of itself
:- object(metaclass,
    instantiates(metaclass)).

    :- public(me/1).
    me(Me) :-
        self(Me).

:- end_object.


local object = { name = "foo", func = function (self) print(self.name) end }

object:func() -- with : sugar
object.func(object) -- without : sugar


Module CheckIt {
      \\ A class definition is a function which return a Group
      \\ We can make groups and we can alter them using Group statement
      \\ Groups may have other groups inside

      Group Alfa {
      Private:
            myvalue=100
      Public:
            Group SetValue {
                  Set (x) {
                        Link parent myvalue to m
                        m<=x
                  }
            }
            Module MyMethod {
                 Read x
                 Print x*.myvalue
            }
      }

      Alfa.MyMethod 5 '500
      Alfa.MyMethod %x=200   ' 20000
      \\ we can copy Alfa to Z
      Z=Alfa
      Z.MyMethod 5
      Z.SetValue=300
      Z.MyMethod 5 ' 1500
      Alfa.MyMethod 5    ' 500
      Dim A(10)
      A(3)=Z
      A(3).MyMethod 5 '1500
      A(3).SetValue=200
      A(3).MyMethod 5 '1000
      \\ get a pointer of group in A(3)
      k->A(3)
      k=>SetValue=100
      A(3).MyMethod 5 '500
      \\ k get pointer to Alfa
      k->Alfa
      k=>SetValue=500
      Alfa.MyMethod 5 '2500
      k->Z
      k=>MyMethod 5 ' 1500
      Z.SetValue=100
      k=>MyMethod 5 ' 500
}
Checkit


Dog = {}
Dog.name = ""
Dog.help = function()
    print "This class represents dogs."
end function
Dog.speak = function()
    print self.name + " says Woof!"
end function

fido = new Dog
fido.name = "Fido"

Dog.help    // calling a "class method"
fido.speak  // calling an "instance method"


class MyClass
	declare static id = 5
	declare MyName

	// constructor
	def MyClass(MyName)
		this.MyName = MyName
	end

	// class method
	def getName()
		return this.MyName
	end

	// static method
	def static getID()
		return id
	end
end

// call the static method
println MyClass.getID()

// instantiate a new MyClass object with the name "test"
// and call the class method
myclass = new(MyClass, "test")
println myclass.getName()


      10 FOR i% = 1 TO 15
      20   PRINT FNcatalan(i%)
      30 NEXT
      40 END
      50 DEF FNcatalan(n%)
      60   IF n% = 0 THEN = 1
      70   = 2 * (2 * n% - 1) * FNcatalan(n% - 1) / (n% + 1)


( out$straight
& ( C
  =
    .   ( F
        =   i prod
          .   !arg:0&1
            |   1:?prod
              & 0:?i
              &   whl
                ' ( 1+!i:~>!arg:?i
                  & !i*!prod:?prod
                  )
              & !prod
        )
      & F$(2*!arg)*(F$(!arg+1)*F$!arg)^-1
  )
& -1:?n
&   whl
  ' ( 1+!n:~>15:?n
    & out$(str$(C !n " = " C$!n))
    )
& out$"recursive, with memoization, without fractions"
& :?seenCs
& ( C
  =   i sum
    .   !arg:0&1
      |   ( !seenCs:? (!arg.?sum) ?
          |   0:?sum
            & -1:?i
            &   whl
              ' ( 1+!i:<!arg:?i
                & C$!i*C$(-1+!arg+-1*!i)+!sum:?sum
                )
            & (!arg.!sum) !seenCs:?seenCs
          )
        & !sum
  )
& -1:?n
&   whl
  ' ( 1+!n:~>15:?n
    & out$(str$(C !n " = " C$!n))
    )
& out$"recursive, without memoization, with fractions"
& ( C
  =
    .   !arg:0&1
      | 2*(2*!arg+-1)*(!arg+1)^-1*C$(!arg+-1)
  )
& -1:?n
&   whl
  ' ( 1+!n:~>15:?n
    & out$(str$(C !n " = " C$!n))
    )
& out$"Using taylor expansion of sqrt(1-4X). (See http://bababadalgharaghtakamminarronnkonnbro.blogspot.in/2012/10/algebraic-type-systems-combinatorial.html)"
& out$(1+(1+-1*tay$((1+-4*X)^1/2,X,16))*(2*X)^-1+-1)
& out$
);


with javascript_semantics
function cart(sequence s)
    sequence res = {}
    for n=2 to length(s) do
        for i=1 to length(s[1]) do
            for j=1 to length(s[2]) do
                res = append(res,s[1][i]&s[2][j])
            end for
        end for
        if length(s)=2 then exit end if
        s[1..2] = {res}
        res = {}
    end for
    return res
end function

?cart({{1,2},{3,4}})
?cart({{3,4},{1,2}})
?cart({{1,2},{}})
?cart({{},{1,2}})
?cart({{1776, 1789},{7, 12},{4, 14, 23},{0, 1}})
?cart({{1, 2, 3},{30},{500, 100}})
?cart({{1, 2, 3},{},{500, 100}})


// Static
MyClass.Method(someParameter);

// Instance
myInstance.Method(someParameter);


ClassName->some_function(); # call class function
instance->some_method(); # call instance method


// Static (known in Pascal as class method)
MyClass.method(someParameter);

// Instance
myInstance.method(someParameter);


// Class
[MyClass method:someParameter];
// or equivalently:
id foo = [MyClass class];
[foo method:someParameter];

// Instance
[myInstance method:someParameter];

// Method with multiple arguments
[myInstance methodWithRed:arg1 green:arg2 blue:arg3];

// Method with no arguments
[myInstance method];


Cat←{ 0⊸<◶⟨1, (𝕊-⟜1)×(¯2+4×⊢)÷1+⊢⟩ 𝕩 }
Fact ← ×´1+↕
Cat1 ← { # direct formula
  ⌊0.5 + (Fact 2×𝕩) ÷ (Fact 𝕩+1) × Fact 𝕩
}
Cat2 ← { # header based recursion
  0: 1;
  (𝕊 𝕩-1)×2×(1-˜2×𝕩)÷𝕩+1
}

Cat¨ ↕15
Cat1¨ ↕15
Cat2¨ ↕15


#include <stdio.h>

typedef unsigned long long ull;

ull binomial(ull m, ull n)
{
	ull r = 1, d = m - n;
	if (d > n) { n = d; d = m - n; }

	while (m > n) {
		r *= m--;
		while (d > 1 && ! (r%d) ) r /= d--;
	}

	return r;
}

ull catalan1(int n) {
	return binomial(2 * n, n) / (1 + n);
}

ull catalan2(int n) {
	int i;
	ull r = !n;

	for (i = 0; i < n; i++)
		r += catalan2(i) * catalan2(n - 1 - i);
	return r;
}

ull catalan3(int n)
{
	return n ? 2 * (2 * n - 1) * catalan3(n - 1) / (1 + n) : 1;
}

int main(void)
{
	int i;
	puts("\tdirect\tsumming\tfrac");
	for (i = 0; i < 16; i++) {
		printf("%d\t%llu\t%llu\t%llu\n", i,
			catalan1(i), catalan2(i), catalan3(i));
	}

	return 0;
}


include ..\Utilitys.pmt

def cart
    ( ) var res
    -1 get var ta -1 del
    -1 get var he -1 del
    ta "" != he "" != and if
        he len nip for
            he swap get var h drop
            ta len nip for
                ta swap get var t drop
                ( h t ) flatten res swap 0 put var res
            endfor
        endfor
        len if res 0 put cart endif
    endif
enddef

/# ---------- MAIN ---------- #/

( ( 1 2 ) ( 3 4 ) ) cart
drop res print nl nl

( ( 1776 1789 ) ( 7 12 ) ( 4 14 23 ) ( 0 1 ) ) cart
drop res print nl nl

( ( 1 2 3 ) ( 30 ) ( 500 100 ) ) cart
drop res print nl nl

( ( 1 2 ) ( ) ) cart
drop res print nl nl


(de 2lists (L1 L2)
   (mapcan
      '((I)
         (mapcar
            '((A) ((if (atom A) list cons) I A))
            L2 ) )
      L1 ) )
(de reduce (L . @)
   (ifn (rest) L (2lists L (apply reduce (rest)))) )
(de cartesian (L . @)
   (and L (rest) (pass reduce L)) )

(println
   (cartesian (1 2)) )
(println
   (cartesian NIL (1 2)) )
(println
   (cartesian (1 2) (3 4)) )
(println
   (cartesian (3 4) (1 2)) )
(println
   (cartesian (1776 1789) (7 12) (4 14 23) (0 1)) )
(println
   (cartesian (1 2 3) (30) (500 100)) )
(println
   (cartesian (1 2 3) NIL (500 100)) )


product([A|_], Bs, [A, B]) :- member(B, Bs).
product([_|As], Bs, X) :- product(As, Bs, X).


say "pi:" .circle~pi
c=.circle~new(1)
say "c~area:" c~area
Do r=2 To 10
 c.r=.circle~new(r)
 End
say .circle~instances('') 'circles were created'

::class circle
::method pi class -- a class method
  return 3.14159265358979323

::method instances class -- another class method
  expose in
  use arg a
  If datatype(in)<>'NUM' Then in=0
  If a<>'' Then
    in+=1
  Return in

::method init
  expose radius
  use arg radius
  self~class~instances('x')

::method area     -- an instance method
  expose radius
  Say self~class
  Say self
  return self~class~pi * radius * radius


# Class method
MyClass->classMethod($someParameter);
# Equivalently using a class name
my $foo = 'MyClass';
$foo->classMethod($someParameter);

# Instance method
$myInstance->method($someParameter);

# Calling a method with no parameters
$myInstance->anotherMethod;

# Class and instance method calls are made behind the scenes by getting the function from
# the package and calling it on the class name or object reference explicitly
MyClass::classMethod('MyClass', $someParameter);
MyClass::method($myInstance, $someParameter);


without js -- (no class in p2js)
class test
    string msg = "this is a test"
    procedure show() ?this.msg end procedure
    procedure inst() ?"this is dynamic" end procedure
end class
test t = new()
t.show()            -- prints "this is a test"
t.inst()            -- prints "this is dynamic"
t.inst = t.show
t.inst()            -- prints "this is a test"


namespace CatalanNumbers
{
    /// <summary>
    /// Class that holds all options.
    /// </summary>
    public class CatalanNumberGenerator
    {
        private static double Factorial(double n)
        {
            if (n == 0)
                return 1;

            return n * Factorial(n - 1);
        }

        public double FirstOption(double n)
        {
            const double topMultiplier = 2;
            return Factorial(topMultiplier * n) / (Factorial(n + 1) * Factorial(n));
        }

        public double SecondOption(double n)
        {
            if (n == 0)
            {
                return 1;
            }
            double sum = 0;
            double i = 0;
            for (; i <= (n - 1); i++)
            {
                sum += SecondOption(i) * SecondOption((n - 1) - i);
            }
            return sum;
        }

        public double ThirdOption(double n)
        {
            if (n == 0)
            {
                return 1;
            }
            return ((2 * (2 * n - 1)) / (n + 1)) * ThirdOption(n - 1);
        }
    }
}

// Program.cs
using System;
using System.Configuration;

// Main program
// Be sure to add the following to the App.config file and add a reference to System.Configuration:
// <?xml version="1.0" encoding="utf-8" ?>
// <configuration>
//  <appSettings>
//    <clear/>
//    <add key="MaxCatalanNumber" value="50"/>
//  </appSettings>
// </configuration>
namespace CatalanNumbers
{
    class Program
    {
        static void Main(string[] args)
        {
            CatalanNumberGenerator generator = new CatalanNumberGenerator();
            int i = 0;
            DateTime initial;
            DateTime final;
            TimeSpan ts;

            try
            {
                initial = DateTime.Now;
                for (; i <= Convert.ToInt32(ConfigurationManager.AppSettings["MaxCatalanNumber"]); i++)
                {
                    Console.WriteLine("CatalanNumber({0}):{1}", i, generator.FirstOption(i));
                }
                final = DateTime.Now;
                ts = final - initial;
                Console.WriteLine("It took {0}.{1} to execute\n", ts.Seconds, ts.Milliseconds);

                i = 0;
                initial = DateTime.Now;
                for (; i <= Convert.ToInt32(ConfigurationManager.AppSettings["MaxCatalanNumber"]); i++)
                {
                    Console.WriteLine("CatalanNumber({0}):{1}", i, generator.SecondOption(i));
                }
                final = DateTime.Now;
                ts = final - initial;
                Console.WriteLine("It took {0}.{1} to execute\n", ts.Seconds, ts.Milliseconds);

                i = 0;
                initial = DateTime.Now;
                for (; i <= Convert.ToInt32(ConfigurationManager.AppSettings["MaxCatalanNumber"]); i++)
                {
                    Console.WriteLine("CatalanNumber({0}):{1}", i, generator.ThirdOption(i));
                }
                final = DateTime.Now;
                ts = final - initial;
                Console.WriteLine("It took {0}.{1} to execute", ts.Seconds, ts.Milliseconds, ts.TotalMilliseconds);
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Stopped at index {0}:", i);
                Console.WriteLine(ex.Message);
                Console.ReadLine();
            }
        }
    }
}


// Static method
MyClass::method($someParameter);
// In PHP 5.3+, static method can be called on a string of the class name
$foo = 'MyClass';
$foo::method($someParameter);

// Instance method
$myInstance->method($someParameter);


obj->method();
obj["method"]();
call_function(obj->method);
call_function(obj["method"]);


CREATE OR REPLACE TYPE myClass AS OBJECT (
    -- A class needs at least one member even though we don't use it
    dummy NUMBER,
    STATIC FUNCTION static_method RETURN VARCHAR2,
    MEMBER FUNCTION instance_method RETURN VARCHAR2
);
/
CREATE OR REPLACE TYPE BODY myClass AS
    STATIC FUNCTION static_method RETURN VARCHAR2 IS
    BEGIN
        RETURN 'Called myClass.static_method';
    END static_method;

    MEMBER FUNCTION instance_method RETURN VARCHAR2 IS
    BEGIN
        RETURN 'Called myClass.instance_method';
    END instance_method;
END;
/

DECLARE
    myInstance myClass;
BEGIN
    myInstance := myClass(NULL);
    DBMS_OUTPUT.put_line( myClass.static_method() );
    DBMS_OUTPUT.put_line( myInstance.instance_method() );
END;/


$Date = Get-Date
$Date.AddDays( 1 )
[System.Math]::Sqrt( 2 )


#if !defined __ALGORITHMS_H__
#define __ALGORITHMS_H__

namespace rosetta
  {
  namespace catalanNumbers
    {
    namespace detail
      {

      class Factorial
        {
        public:
          unsigned long long operator()(unsigned n)const;
        };

      class BinomialCoefficient
        {
        public:
          unsigned long long operator()(unsigned n, unsigned k)const;
        };

      } //namespace detail

    class CatalanNumbersDirectFactorial
      {
      public:
        CatalanNumbersDirectFactorial();
        unsigned long long operator()(unsigned n)const;
      private:
        detail::Factorial factorial;
      };

    class CatalanNumbersDirectBinomialCoefficient
      {
      public:
        CatalanNumbersDirectBinomialCoefficient();
        unsigned long long operator()(unsigned n)const;
      private:
        detail::BinomialCoefficient binomialCoefficient;
      };

    class CatalanNumbersRecursiveSum
      {
      public:
        CatalanNumbersRecursiveSum();
        unsigned long long operator()(unsigned n)const;
      };

    class CatalanNumbersRecursiveFraction
      {
      public:
        CatalanNumbersRecursiveFraction();
        unsigned long long operator()(unsigned n)const;
      };

    }   //namespace catalanNumbers
  }     //namespace rosetta

#endif //!defined __ALGORITHMS_H__


  [ [] unrot
    swap witheach
      [ over witheach
          [ over nested
            swap nested join
            nested dip rot join
            unrot ]
      drop ] drop ]             is cartprod ( [ [ --> [ )

  ' [ 1 2 ] ' [ 3 4 ] cartprod echo cr
  ' [ 3 4 ] ' [ 1 2 ] cartprod echo cr
  ' [ 1 2 ] ' [     ] cartprod echo cr
  ' [     ] ' [ 1 2 ] cartprod echo cr


one_w_many <- function(one, many) lapply(many, function(x) c(one,x))

# Let's define an infix operator to perform a cartesian product.

"%p%" <- function( a, b ) {
  p = c( sapply(a, function (x) one_w_many(x, b) ) )
  if (is.null(unlist(p))) list() else p}

display_prod <-
  function (xs) { for (x in xs) cat( paste(x, collapse=", "), "\n" ) }

fmt_vec <- function(v) sprintf("(%s)", paste(v, collapse=', '))

go <- function (...) {
  cat("\n", paste( sapply(list(...),fmt_vec), collapse=" * "), "\n")
  prod = Reduce( '%p%', list(...) )
  display_prod( prod ) }


// define a rudimentary class
class HelloWorld
{
    public static void sayHello()
    {
        println("Hello, world!");
    }
    public void sayGoodbye()
    {
        println("Goodbye, cruel world!");
    }
}

// call the class method
HelloWorld.sayHello();

// create an instance of the class
HelloWorld hello = new HelloWorld();

// and call the instance method
hello.sayGoodbye();


class MyClass(object):
	@classmethod
	def myClassMethod(self, x):
		pass
	@staticmethod
	def myStaticMethod(x):
		pass
	def myMethod(self, x):
		return 42 + x

myInstance = MyClass()

# Instance method
myInstance.myMethod(someParameter)
# A method can also be retrieved as an attribute from the class, and then explicitly called on an instance:
MyClass.myMethod(myInstance, someParameter)

# Class or static methods
MyClass.myClassMethod(someParameter)
MyClass.myStaticMethod(someParameter)
# You can also call class or static methods on an instance, which will simply call it on the instance's class
myInstance.myClassMethod(someParameter)
myInstance.myStaticMethod(someParameter)


( ---------------- zen object orientation -------------- )

[ immovable
  ]this[ swap do ]done[ ] is object            (   -->   )

[ ]'[ ]                   is method            (   --> [ )

[ method
    [ dup share
      swap put ] ]        is localise          (   --> [ )

[ method [ release ] ]    is delocalise        (   --> [ )

( -------------- example: counter methods -------------- )

( to create a counter object, use:
           "[ object 0 ]  is 'name' ( [ -->   )"         )

[ method
    [ 0 swap replace ] ]  is reset-counter     (   --> [ )

[ method
    [ 1 swap tally ] ]    is increment-counter (   --> [ )

[ method [ share ] ]      is report-counter    (   --> [ )

( -------------------- demonstration ------------------- )

say 'Creating counter object: "mycounter".' cr cr
[ object 0 ]              is mycounter         ( [ -->   )

say "Initial value of mycounter: "
report-counter mycounter echo cr cr

say "Incrementing mycounter three times." cr
3 times [ increment-counter mycounter ]

say "Current value of mycounter: "
report-counter mycounter echo cr cr

say "Localising mycounter." cr cr
localise mycounter

say "    Current value of mycounter: "
report-counter mycounter echo cr cr

say "    Resetting mycounter." cr
reset-counter mycounter

say "    Current value of mycounter: "
report-counter mycounter echo cr cr

say "    Incrementing mycounter six times." cr
6 times [ increment-counter mycounter ]

say "    Current value of mycounter: "
report-counter mycounter echo cr cr

say "Delocalising mycounter." cr cr
delocalise mycounter

say "Current value of mycounter: "
report-counter mycounter echo cr cr

say "Resetting mycounter." cr
reset-counter mycounter

say "Current value of mycounter: "
report-counter mycounter echo cr cr


#lang racket/gui

(define timer (new timer%))
(send timer start 100)


class Thing {
  method regular-example() { say 'I haz a method' }

  multi method multi-example() { say 'No arguments given' }
  multi method multi-example(Str $foo) { say 'String given' }
  multi method multi-example(Int $foo) { say 'Integer given' }
};

# 'new' is actually a method, not a special keyword:
my $thing = Thing.new;

# No arguments: parentheses are optional
$thing.regular-example;
$thing.regular-example();
$thing.multi-example;
$thing.multi-example();

# Arguments: parentheses or colon required
$thing.multi-example("This is a string");
$thing.multi-example: "This is a string";
$thing.multi-example(42);
$thing.multi-example: 42;

# Indirect (reverse order) method call syntax: colon required
my $foo = new Thing: ;
multi-example $thing: 42;


(defun catalan1 (n)
  ;; factorial. CLISP actually has "!" defined for this
  (labels ((! (x) (if (zerop x) 1 (* x (! (1- x))))))
    (/ (! (* 2 n)) (! (1+ n)) (! n))))

;; cache
(defparameter *catalans* (make-array 5
				     :fill-pointer 0
				     :adjustable t
				     :element-type 'integer))
(defun catalan2 (n)
    (if (zerop n) 1
    ;; check cache
    (if (< n (length *catalans*)) (aref *catalans* n)
      (loop with c = 0 for i from 0 to (1- n) collect
	    (incf c (* (catalan2 i) (catalan2 (- n 1 i))))
	    ;; lower values always get calculated first, so
	    ;; vector-push-extend is safe
	    finally (progn (vector-push-extend c *catalans*) (return c))))))

(defun catalan3 (n)
  (if (zerop n) 1 (/ (* 2 (+ n n -1) (catalan3 (1- n))) (1+ n))))

;;; test all three methods
(loop for f in (list #'catalan1 #'catalan2 #'catalan3)
      for i from 1 to 3 do
      (format t "~%Method ~d:~%" i)
      (dotimes (i 16) (format t "C(~2d) = ~d~%" i (funcall f i))))


#lang racket/base
(require rackunit
         ;; usually, included in "racket", but we're using racket/base so we
         ;; show where this comes from
         (only-in racket/list cartesian-product))
;; these tests will pass silently
(check-equal? (cartesian-product '(1 2) '(3 4))
             '((1 3) (1 4) (2 3) (2 4)))
(check-equal? (cartesian-product '(3 4) '(1 2))
             '((3 1) (3 2) (4 1) (4 2)))
(check-equal? (cartesian-product '(1 2) '()) '())
(check-equal? (cartesian-product '() '(1 2)) '())

;; these will print
(cartesian-product '(1776 1789) '(7 12) '(4 14 23) '(0 1))
(cartesian-product '(1 2 3) '(30) '(500 100))
(cartesian-product '(1 2 3) '() '(500 100))


# cartesian product of two lists using the X cross meta-operator
say (1, 2) X (3, 4);
say (3, 4) X (1, 2);
say (1, 2) X ( );
say ( )    X ( 1, 2 );

# cartesian product of variable number of lists using
# the [X] reduce cross meta-operator
say [X] (1776, 1789), (7, 12), (4, 14, 23), (0, 1);
say [X] (1, 2, 3), (30), (500, 100);
say [X] (1, 2, 3), (),   (500, 100);


new point { print() }
Class Point
        x = 10  y = 20  z = 30
        func print see x + nl + y + nl + z + nl


# Class method
MyClass.some_method(some_parameter)

# Class may be computed at runtime
foo = MyClass
foo.some_method(some_parameter)

# Instance method
my_instance.a_method(some_parameter)

# The parentheses are optional
my_instance.a_method some_parameter

# Calling a method with no parameters
my_instance.another_method


struct Foo;

impl Foo {
    // implementation of an instance method for struct Foo
    // returning the answer to life
    fn get_the_answer_to_life(&self) -> i32 {
        42
    }

    // implementation of a static method for struct Foo
    // returning a new instance object
    fn new() -> Foo {
        println!("Hello, world!");
        Foo // returning the new Foo object
    }
}

fn main() {
    // create the instance object foo,
    // by calling the static method new of struct Foo
    let foo = Foo::new();

    // get the answer to life
    // by calling the instance method of object foo
    println!("The answer to life is {}.", foo.get_the_answer_to_life());

    // Note that in Rust, methods still work on references to the object.
    // Rust will automatically do the appropriate dereferencing to get the method to work:
    let lots_of_references = &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&foo;
    println!("The answer to life is still {}." lots_of_references.get_the_answer_to_life());
}


/* This class implicitly includes a constructor which accepts an Int and
 *  creates "val variable1: Int" with that value.
 */
class MyClass(val memberVal: Int) { // Acts like a getter, getter automatically generated.
  var variable2 = "asdf" // Another instance variable; a public mutable this time
  def this() = this(0) // An auxilliary constructor that instantiates with a default value
}

object HelloObject {
  val s = "Hello" // Not private, so getter auto-generated
}

/** Demonstrate use of our example class.
 */
object Call_an_object_method extends App {
  val s = "Hello"
  val m = new MyClass
  val n = new MyClass(3)

  assert(HelloObject.s == "Hello") // "Hello" by object getterHelloObject
  assert(m.memberVal == 0)
  assert(n.memberVal == 3)
  println("Successfully completed without error.")
}


class MyClass {
    method foo(arg) { say arg }
}

var arg = 42;

# Call a class method
MyClass.foo(arg);

# Alternatively, using an expression for the method name
MyClass.(:foo)(arg);

# Create an instance
var instance = MyClass();

# Instance method
instance.foo(arg);

# Alternatively, by using an expression for the method name
instance.(:foo)(arg);

# Alternatively, by asking for a method
instance.method(:foo)(arg);


require "big"
require "benchmark"

def factorial(n : BigInt) : BigInt
  (1..n).product(1.to_big_i)
end

def factorial(n : Int32 | Int64)
  factorial n.to_big_i
end

# direct

def catalan_direct(n)
  factorial(2*n) / (factorial(n + 1) * factorial(n))
end

# recursive

def catalan_rec1(n)
  return 1 if n == 0
  (0...n).reduce(0) do |sum, i|
    sum + catalan_rec1(i) * catalan_rec1(n - 1 - i)
  end
end

def catalan_rec2(n)
  return 1 if n == 0
  2*(2*n - 1) * catalan_rec2(n - 1) / (n + 1)
end

# performance and results

Benchmark.bm do |b|
  b.report("catalan_direct") { 16.times { |n| catalan_direct(n) } }
  b.report("catalan_rec1") { 16.times { |n| catalan_rec1(n) } }
  b.report("catalan_rec2") { 16.times { |n| catalan_rec2(n) } }
end

puts "\n       direct     rec1     rec2"
16.times { |n| puts "%2d :%9d%9d%9d" % [n, catalan_direct(n), catalan_rec1(n), catalan_rec2(n)] }


import std.stdio, std.algorithm, std.bigint, std.functional, std.range;

auto product(R)(R r) { return reduce!q{a * b}(1.BigInt, r); }

const cats1 = sequence!((a, n) => iota(n+2, 2*n+1).product / iota(1, n+1).product)(1);

BigInt cats2a(in uint n) {
    alias mcats2a = memoize!cats2a;
    if (n == 0) return 1.BigInt;
    return n.iota.map!(i => mcats2a(i) * mcats2a(n - 1 - i)).sum;
}

const cats2 = sequence!((a, n) => n.cats2a);

const cats3 = recurrence!q{ (4*n - 2) * a[n - 1] / (n + 1) }(1.BigInt);

void main() {
    foreach (cats; TypeTuple!(cats1, cats2, cats3))
        cats.take(15).writeln;
}


/*REXX program  calculates  the   Cartesian product   of two  arbitrary-sized  lists.   */
@.=                                              /*assign the default value to  @. array*/
parse arg @.1                                    /*obtain the optional value of  @.1    */
if @.1=''  then do;  @.1= "{1,2} {3,4}"          /*Not specified?  Then use the defaults*/
                     @.2= "{3,4} {1,2}"          /* "      "         "   "   "      "   */
                     @.3= "{1,2} {}"             /* "      "         "   "   "      "   */
                     @.4= "{}    {3,4}"          /* "      "         "   "   "      "   */
                     @.5= "{1,2} {3,4,5}"        /* "      "         "   "   "      "   */
                end
                                                 /* [↓]  process each of the  @.n values*/
  do n=1  while @.n \= ''                        /*keep processing while there's a value*/
  z= translate( space( @.n, 0),  ,  ',')         /*translate the  commas  to blanks.    */
     do #=1  until z==''                         /*process each elements in first list. */
     parse var  z   '{'  x.#  '}'   z            /*parse the list  (contains elements). */
     end   /*#*/
  $=
     do       i=1   for #-1                      /*process the subsequent lists.        */
       do     a=1   for words(x.i)               /*obtain the elements of the first list*/
         do   j=i+1 for #-1                      /*   "    "  subsequent lists.         */
           do b=1   for words(x.j)               /*   "    " elements of subsequent list*/
           $=$',('word(x.i, a)","word(x.j, b)')' /*append partial Cartesian product ──►$*/
           end   /*b*/
         end     /*j*/
       end       /*a*/
     end         /*i*/
  say 'Cartesian product of '       space(@.n)       " is ───► {"substr($, 2)'}'
  end            /*n*/                           /*stick a fork in it,  we're all done. */


" Class "
MyClass selector: someArgument .
" or equivalently "
foo := MyClass .
foo selector: someArgument.

" Instance "
myInstance selector: someArgument.

" Message with multiple arguments "
myInstance fooWithRed:arg1 green:arg2 blue:arg3 .

" Message with no arguments "
myInstance selector.

" Binary (operator) message"
myInstance + argument .


	SomeClass {

		*someClassMethod {

		}

		someInstanceMethod {

		}

	}

	SomeClass.someClassMethod;

	a = SomeClass.new;
	a.someInstanceMethod;


// Class
MyClass.method(someParameter)
// or equivalently:
let foo = MyClass.self
foo.method(someParameter)

// Instance
myInstance.method(someParameter)

// Method with multiple arguments
myInstance.method(red:arg1, green:arg2, blue:arg3)


package require Tcl 8.6
# "Static" (on class object)
MyClass mthd someParameter

# Instance
$myInstance mthd someParameter


# create an instance of the built-in file class
decl file f

# call the file.open method
f.open "filename.txt"


Option Explicit

Sub Method_1(Optional myStr As String)
Dim strTemp As String
    If myStr <> "" Then strTemp = myStr
    Debug.Print strTemp
End Sub

Static Sub Method_2(Optional myStr As String)
Dim strTemp As String
    If myStr <> "" Then strTemp = myStr
    Debug.Print strTemp
End Sub


func catalan n . ans .
  if n = 0
    ans = 1
  else
    call catalan n - 1 h
    ans = 2 * (2 * n - 1) * h div (1 + n)
  .
.
for i range 15
  call catalan i h
  print h
.


# Project : Cartesian product of two or more lists

list1 = [[1,2],[3,4]]
list2 = [[3,4],[1,2]]
cartesian(list1)
cartesian(list2)

func cartesian(list1)
     for n = 1 to len(list1[1])
         for m = 1 to len(list1[2])
             see "(" + list1[1][n] + ", " + list1[2][m] + ")" + nl
         next
      next
      see nl


class MyClass {
    construct new() {}
    method() { System.print("instance method called") }
    static method() { System.print("static method called") }
}

var mc = MyClass.new()
mc.method()
MyClass.method()


class MyClass {
	construct=func(self,Props){
		self:Props=Props;
	}{Props={}}
	GetProp=func(self,Name){
		send self.Props[Name];
	}
}

set Class = new MyClass with [{Name="MyClass Name"}];
log(Class::GetProp("Name"));


(DEFINE-CLASS MY-CLASS)

(DEFINE-CLASS-METHOD (MY-CLASS 'DO-SOMETHING-WITH SOME-PARAMETER)
    (DISPLAY "I am the class -- ")
    (DISPLAY SELF)
    (NEWLINE)
    (DISPLAY "You sent me the parameter ")
    (DISPLAY SOME-PARAMETER)
    (NEWLINE))

(DEFINE-METHOD (MY-CLASS 'DO-SOMETHING-WITH SOME-PARAMETER)
    (DISPLAY "I am an instance of the class --  ")
    (DISPLAY SELF)
    (NEWLINE)
    (DISPLAY "You sent me the parameter ")
    (DISPLAY SOME-PARAMETER)
    (NEWLINE))

(MY-CLASS 'DO-SOMETHING-WITH 'FOO)

(DEFINE MY-INSTANCE (MY-CLASS 'NEW))

(MY-INSTANCE 'DO-SOMETHING-WITH 'BAR)


const assert = @import("std").debug.assert;

pub const ID = struct {
    name: []const u8,
    age: u7,

    const Self = @This();

    pub fn init(name: []const u8, age: u7) Self {
        return Self{
            .name = name,
            .age = age,
        };
    }

    pub fn getAge(self: Self) u7 {
        return self.age;
    }
};

test "call an object method" {
    // Declare an instance of a struct by using a struct method.
    const person1 = ID.init("Alice", 18);

    // Or by declaring it manually.
    const person2 = ID{
        .name = "Bob",
        .age = 20,
    };

    assert(person1.getAge() == 18);
    assert(ID.getAge(person2) == 20);
}


class C{var v; fcn f{v}}
C.f() // call function f in class C
C.v=5; c2:=C();    // create new instance of C
println(C.f()," ",c2.f()) //-->5 Void
C.f.isStatic //--> False

class [static] D{var v=123; fcn f{v}}
D.f(); D().f(); // both return 123
D.f.isStatic //-->False

class E{var v; fcn f{}} E.f.isStatic //-->True


  [Calculation of Catalan numbers.
   EDSAC program, Initial Orders 2.]

  [Define where to store the list of Catalan numbers.]
            T   54 K  [store address in location 54, so that values
                       are accessed by code letter C (for Catalan)]
            P  200 F  [<------ address here]

  [Modification of library subroutine P7.
   Prints signed integer up to 10 digits, right-justified.
   54 storage locations; working position 4D.
   Must be loaded at an even address.
   Input: Number is at 0D.]
            T   56 K
  [email protected]@[email protected]@[email protected]@[email protected]#@[email protected]
  [email protected]@[email protected]@[email protected]@[email protected]@
  [email protected]@[email protected][email protected]@[email protected]@

     [Main routine]
            T  120 K  [load at 120]
            G      K  [set @ (theta) to load address]
     [Variables]
      [0]   P      F  [index of Catalan number]
     [Constants]
      [1]   P    7 D  [maximum index required]
      [2]   P      D  [single-word 1]
      [3]   P    2 F  [to change addresses by 2]
      [4]   H     #C  [these 3 are used to manufacture EDSAC orders]
      [5]   T     #C
      [6]   V     #C
      [7]   K 4096 F  [(1) add to change T order into H order
                       (2) teleprinter null]
      [8]   #      F  [figures shift]
      [9]   !      F  [space]
     [10]   @      F  [carriage return]
     [11]   &      F  [line feed]

           [Enter with acc = 0]
     [12]   O    8 @  [set teleprinter to figures]
            T    4 D  [clear 5F and sandwich bit]
            A    2 @  [load single-word 1]
            T    4 F  [store as double word at 4D; clear acc]
           [Here with index in acc, Catalan number in 4D]
     [16]   U      @  [store index]
            L    1 F  [times 4 by shifting]
            A    5 @  [make T order to store Catalan number]
            U   27 @  [plant in code]
            A    7 @  [make H order with same address]
            U   45 @  [plant in code]
            S   47 @  [make A order with same address]
            T   34 @  [plant in code]
            A    6 @  [load V order for start of list]
            T   46 @  [plant in code]
            A    4 D  [Catalan number from temp store]
     [27]   T     #C  [store in list (manufactured order)]
            T      D  [clear 1F and sandwich bit]
            A      @  [load single-word index]
            T      F  [store as double word at 0D]
     [31]   A   31 @  [for return from print subroutine]
            G   56 F  [print index]
            O    9 @  [followed by space]
     [34]   A     #C  [load Catalan number (manufactured order)]
            T      D  [to 0D for printing]
     [36]   A   36 @  [for return from print subroutine]
            G   56 F  [print Catalan number]
            O   10 @  [followed by new line]
            O   11 @
            T    4 D  [clear partial sum]
            A      @  [load index]
            S    1 @  [reached the maximum?]
            E   64 @  [if so, jump to exit]
            [Inner loop to compute sum of products C{i}*C(n-1}]
     [44]   T      F  [clear acc]
     [45]   H     #C  [C{n-i} to mult reg (manufactured order)]
     [46]   V     #C  [acc := C{i}*C{n-i} (manufactiured order)]
           [Multiply product by 2^34 (see preamble). The 'L F' order is
            also exploited above to convert an H order into an A order.]
     [47]   L      F  [shift acc left by 13 (the maximum available)]
            L      F  [shift 13 more]
            L   64 F  [shift 8 more, total 34]
            A    4 D  [add partial sum]
            T    4 D  [update partial sum]
            A   46 @  [inc i in V order]
            A    3 @
            T   46 @
            A   45 @  [dec (n - i) in H order]
            S    3 @
            U   45 @
            S    4 @  [is (n - i) now negative?]
            E   44 @  [if not, loop back]
           [Here with latest Catalan number in temp store 4D]
            T      F  [clear acc]
            A      @  [load index]
            A    2 @  [add 1]
            E   16 @  [back to start of outer loop]
     [64]   O    7 @  [exit; print null to flush teleprinter buffer]
            Z      F  [stop]
            E   12 Z  [define entry point]
            P      F  [acc = 0 on entry]


class
	APPLICATION

create
	make

feature {NONE}

	make
		do
			across
				0 |..| 14 as c
			loop
				io.put_double (nth_catalan_number (c.item))
				io.new_line
			end
		end

	nth_catalan_number (n: INTEGER): DOUBLE
			--'n'th number in the sequence of Catalan numbers.
		require
			n_not_negative: n >= 0
		local
			s, t: DOUBLE
		do
			if n = 0 then
				Result := 1.0
			else
				t := 4 * n.to_double - 2
				s := n.to_double + 1
				Result := t / s * nth_catalan_number (n - 1)
			end
		end

end


with Ada.Text_IO;   use Ada.Text_IO;
with Interfaces;    use Interfaces;
with Interfaces.C;  use Interfaces.C;
with System;        use System;

with Ada.Unchecked_Conversion;

procedure Shared_Library_Call is
   --
   -- Interface to kernel32.dll which is responsible for loading DLLs under Windows.
   -- There are ready to use Win32 bindings. We don't want to use them here.
   --
   type HANDLE is new Unsigned_32; -- on x64 system, replace by Unsigned_64 to make it work
   function LoadLibrary (lpFileName : char_array) return HANDLE;
   pragma Import (stdcall, LoadLibrary, "LoadLibrary", "_LoadLibraryA"); -- Ada95 does not have the @n suffix.

   function GetProcAddress (hModule : HANDLE; lpProcName : char_array)
      return Address;
   pragma Import (stdcall, GetProcAddress, "GetProcAddress", "_GetProcAddress"); --
   --
   -- The interface of the function we want to call. It is a pointer (access type)
   -- because we will link it dynamically. The function is from User32.dll
   --
   type MessageBox is access function
        (  hWnd      : Address     := Null_Address;
           lpText    : char_array;
           lpCaption : char_array  := To_C ("Greeting");
           uType     : Unsigned_16 := 0
        )  return Integer_16;
   pragma Convention (Stdcall, MessageBox);
   function To_MessageBox is new Ada.Unchecked_Conversion (Address, MessageBox);

   Library : HANDLE  := LoadLibrary (To_C ("user32.dll"));
   Pointer : Address := GetProcAddress (Library, To_C ("MessageBoxA"));
begin
   if Pointer /= Null_Address then
      declare
         Result : Integer_16;
      begin
         Result := To_MessageBox (Pointer) (lpText => To_C ("Hello!"));
      end;
   else
      Put_Line ("Unable to load the library " & HANDLE'Image (Library));
   end if;
end Shared_Library_Call;


fn cartesian_product(lists: &Vec<Vec<u32>>) -> Vec<Vec<u32>> {
    let mut res = vec![];

    let mut list_iter = lists.iter();
    if let Some(first_list) = list_iter.next() {
        for &i in first_list {
            res.push(vec![i]);
        }
    }
    for l in list_iter {
        let mut tmp = vec![];
        for r in res {
            for &el in l {
                let mut tmp_el = r.clone();
                tmp_el.push(el);
                tmp.push(tmp_el);
            }
        }
        res = tmp;
    }
    res
}

fn main() {
    let cases = vec![
        vec![vec![1, 2], vec![3, 4]],
        vec![vec![3, 4], vec![1, 2]],
        vec![vec![1, 2], vec![]],
        vec![vec![], vec![1, 2]],
        vec![vec![1776, 1789], vec![7, 12], vec![4, 14, 23], vec![0, 1]],
        vec![vec![1, 2, 3], vec![30], vec![500, 100]],
        vec![vec![1, 2, 3], vec![], vec![500, 100]],
    ];
    for case in cases {
        println!(
            "{}\n{:?}\n",
            case.iter().map(|c| format!("{:?}", c)).collect::<Vec<_>>().join(" × "),
            cartesian_product(&case)
        )
    }
}


def cartesianProduct[T](lst: List[T]*): List[List[T]] = {

  /**
    * Prepend single element to all lists of list
    * @param e single elemetn
    * @param ll list of list
    * @param a accumulator for tail recursive implementation
    * @return list of lists with prepended element e
    */
  def pel(e: T,
          ll: List[List[T]],
          a: List[List[T]] = Nil): List[List[T]] =
    ll match {
      case Nil => a.reverse
      case x :: xs => pel(e, xs, (e :: x) :: a )
    }

  lst.toList match {
    case Nil => Nil
    case x :: Nil => List(x)
    case x :: _ =>
      x match {
        case Nil => Nil
        case _ =>
          lst.par.foldRight(List(x))( (l, a) =>
            l.flatMap(pel(_, a))
          ).map(_.dropRight(x.size))
      }
  }
}


defmodule Catalan do
  def cat(n), do: div( factorial(2*n), factorial(n+1) * factorial(n) )

  defp factorial(n), do: fac1(n,1)

  defp fac1(0, acc), do: acc
  defp fac1(n, acc), do: fac1(n-1, n*acc)

  def cat_r1(0), do: 1
  def cat_r1(n), do: Enum.sum(for i <- 0..n-1, do: cat_r1(i) * cat_r1(n-1-i))

  def cat_r2(0), do: 1
  def cat_r2(n), do: div(cat_r2(n-1) * 2 * (2*n - 1), n + 1)

  def test do
    range = 0..14
    :io.format "Directly:~n~p~n",            [(for n <- range, do: cat(n))]
    :io.format "1st recusive method:~n~p~n", [(for n <- range, do: cat_r1(n))]
    :io.format "2nd recusive method:~n~p~n", [(for n <- range, do: cat_r2(n))]
  end
end

Catalan.test


-module(catalan).

-export([test/0]).

cat(N) ->
   factorial(2 * N) div (factorial(N+1) * factorial(N)).

factorial(N) ->
   fac1(N,1).

fac1(0,Acc) ->
   Acc;
fac1(N,Acc) ->
   fac1(N-1, N * Acc).

cat_r1(0) ->
   1;
cat_r1(N) ->
   lists:sum([cat_r1(I)*cat_r1(N-1-I) || I <- lists:seq(0,N-1)]).

cat_r2(0) ->
   1;
cat_r2(N) ->
   cat_r2(N - 1) * (2 * ((2 * N) - 1)) div (N + 1).

test() ->
    TestList = lists:seq(0,14),
    io:format("Directly:\n~p\n",[[cat(N) || N <- TestList]]),
    io:format("1st recusive method:\n~p\n",[[cat_r1(N) || N <- TestList]]),
    io:format("2nd recusive method:\n~p\n",[[cat_r2(N) || N <- TestList]]).


getCurlVersion: function [][
    try? [
        call.external:'curl "curl_version" .expect: :string []
    ]
    else [
        "library not found"
    ]
]

print ["curl version:" getCurlVersion]


ahkdll := DllCall("LoadLibrary", "str", "AutoHotkey.dll")
clientHandle := DllCall("AutoHotkey\ahkdll", "str", "dllclient.ahk", "str"
, "", "str", "parameter1 parameter2", "Cdecl Int")


' Call a dynamic library function
PROTO j0
bessel0 = j0(1.0)
PRINT bessel0


(define cartesian-product (lambda (xs ys)
 (if (or (zero? (length xs)) (zero? (length ys)))
     '()
     (fold append (map (lambda (x) (map (lambda (y) (list x y)) ys)) xs)))))

(define nary-cartesian-product (lambda (ls)
 (if (fold (lambda (a b) (or a b)) (map (compose zero? length) ls))
     '()
     (map flatten (fold cartesian-product ls)))))

> (cartesian-product '(1 2) '(3 4))
((1 3) (1 4) (2 3) (2 4))
> (cartesian-product '(3 4) '(1 2))
((3 1) (3 2) (4 1) (4 2))
> (cartesian-product '(1 2) '())
()
> (cartesian-product '() '(1 2))
()
> (nary-cartesian-product '((1 2)(a b)(x y)))
((1 a x) (1 a y) (1 b x) (1 b y) (2 a x) (2 a y) (2 b x) (2 b y))


PROGRAM CATALAN

PROCEDURE CATALAN(N->RES)
   RES=1
   FOR I=1 TO N DO
      RES=RES*2*(2*I-1)/(I+1)
   END FOR
END PROCEDURE

BEGIN
   FOR N=0 TO 15 DO
      CATALAN(N->RES)
      PRINT(N;"=";RES)
   END FOR
END PROGRAM


--Catalan number task from Rosetta Code wiki
--User:Lnettnay

--function from factorial task
function factorial(integer n)
atom f = 1
while n > 1 do
        f *= n
        n -= 1
end while

return f
end function

function catalan(integer n)
atom numerator = factorial(2 * n)
atom denominator = factorial(n+1)*factorial(n)
return numerator/denominator
end function

for i = 0 to 15 do
        ? catalan(i)
end for


SYS "MessageBox", @hwnd%, "This is a test message", 0, 0


#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>

int myopenimage(const char *in)
{
  static int handle=0;
  fprintf(stderr, "internal openimage opens %s...\n", in);
  return handle++;
}

int main()
{
  void *imglib;
  int (*extopenimage)(const char *);
  int imghandle;

  imglib = dlopen("./fakeimglib.so", RTLD_LAZY);
  if ( imglib != NULL ) {
    /* extopenimage = (int (*)(const char *))dlsym(imglib,...)
       "man dlopen" says that C99 standard leaves casting from
       "void *" to a function pointer undefined. The following is the
       POSIX.1-2003 workaround found in man */
    *(void **)(&extopenimage) = dlsym(imglib, "openimage");
    /* the following works with gcc, gives no warning even with
       -Wall -std=c99 -pedantic options... :D */
    /* extopenimage = dlsym(imglib, "openimage"); */
    imghandle = extopenimage("fake.img");
  } else {
    imghandle = myopenimage("fake.img");
  }
  printf("opened with handle %d\n", imghandle);
  /* ... */
  if (imglib != NULL ) dlclose(imglib);
  return EXIT_SUCCESS;
}


using System.Runtime.InteropServices;

class Program {
    [DllImport("fakelib.dll")]
    public static extern int fakefunction(int args);

    static void Main(string[] args) {
        int r = fakefunction(10);
    }
}


-- set up list 1
CREATE TABLE L1 (VALUE INTEGER);
INSERT INTO L1 VALUES (1);
INSERT INTO L1 VALUES (2);
-- set up list 2
CREATE TABLE L2 (VALUE INTEGER);
INSERT INTO L2 VALUES (3);
INSERT INTO L2 VALUES (4);
-- get the product
SELECT * FROM L1, L2;


Seq.unfold(fun (c,n) -> let cc = 2*(2*n-1)*c/(n+1) in Some(c,(cc,n+1))) (1,1) |> Seq.take 15 |> Seq.iter (printf "%i, ")


USING: kernel math math.combinatorics prettyprint ;

: catalan ( n -- n ) [ 1 + recip ] [ 2 * ] [ nCk * ] tri ;

15 [ catalan . ] each-integer


class Main
{
  static Int factorial (Int n)
  {
    Int res := 1
    if (n>1)
      (2..n).each |i| { res *= i }
    return res
  }

  static Int catalanA (Int n)
  {
    return factorial(2*n)/(factorial(n+1) * factorial(n))
  }

  static Int catalanB (Int n)
  {
    if (n == 0)
    {
      return 1
    }
    else
    {
      sum := 0
      n.times |i| { sum += catalanB(i) * catalanB(n-1-i) }
      return sum
    }
  }

  static Int catalanC (Int n)
  {
    if (n == 0)
    {
      return 1
    }
    else
    {
      return catalanC(n-1)*2*(2*n-1)/(n+1)
    }
  }

  public static Void main ()
  {
    (1..15).each |n|
    {
      echo (n.toStr.padl(4) +
            catalanA(n).toStr.padl(10) +
            catalanB(n).toStr.padl(10) +
            catalanC(n).toStr.padl(10))
    }
  }
}


       identification division.
       program-id. callsym.

       data division.
       working-storage section.
       01 handle usage pointer.
       01 addr   usage program-pointer.

       procedure division.
       call "dlopen" using
           by reference null
           by value 1
           returning handle
           on exception
               display function exception-statement upon syserr
               goback
       end-call
       if handle equal null then
           display function module-id ": error getting dlopen handle"
             upon syserr
           goback
       end-if

       call "dlsym" using
           by value handle
           by content z"perror"
           returning addr
       end-call
       if addr equal null then
           display function module-id ": error getting perror symbol"
              upon syserr
       else
           call addr returning omitted
       end-if

       goback.
       end program callsym.


CL-USER> (cffi:load-foreign-library "libX11.so")
#<CFFI::FOREIGN-LIBRARY {1004F4ECC1}>
CL-USER> (cffi:foreign-funcall "XOpenDisplay"
                               :string #+sbcl (sb-posix:getenv "DISPLAY")
                                       #-sbcl ":0.0"
                               :pointer)
#.(SB-SYS:INT-SAP #X00650FD0)


libm = LibC.dlopen("libm.so.6", LibC::RTLD_LAZY)
sqrtptr = LibC.dlsym(libm, "sqrt") unless libm.null?

if sqrtptr
  sqrtproc = Proc(Float64, Float64).new sqrtptr, Pointer(Void).null
  at_exit { LibC.dlclose(libm) }
else
  sqrtproc = ->Math.sqrt(Float64)
end

puts "the sqrt of 4 is #{sqrtproc.call(4.0)}"


fun prodList (nil,     _) = nil
  | prodList ((x::xs), ys) = map (fn y => (x,y)) ys @ prodList (xs, ys)

fun naryProdList zs = foldl (fn (xs, ys) => map op:: (prodList (xs, ys))) [[]] (rev zs)


Func Catalan(n)=(2*n)!/((n+1)!*n!).;
for i=1 to 15 do !Catalan(i);!' ' od;


: catalan ( n -- )  1 swap 1+ 1 do dup cr .  i 2* 1- 2*  i 1+ */ loop drop ;


pragma(lib, "user32.lib");

import std.stdio, std.c.windows.windows;

extern(Windows) UINT GetDoubleClickTime();

void main() {
    writeln(GetDoubleClickTime());
}


int add(int num1, int num2) {
	return num1 + num2;
}


procedure DoSomething; external 'MYLIB.DLL';


c-library math

s" m" add-lib
\c #include <math.h>
c-function gamma tgamma r -- r

end-c-library


func + <T>(el: T, arr: [T]) -> [T] {
  var ret = arr

  ret.insert(el, at: 0)

  return ret
}

func cartesianProduct<T>(_ arrays: [T]...) -> [[T]] {
  guard let head = arrays.first else {
    return []
  }

  let first = Array(head)

  func pel(
    _ el: T,
    _ ll: [[T]],
    _ a: [[T]] = []
  ) -> [[T]] {
    switch ll.count {
    case 0:
      return a.reversed()
    case _:
      let tail = Array(ll.dropFirst())
      let head = ll.first!

      return pel(el, tail, el + head + a)
    }
  }

  return arrays.reversed()
    .reduce([first], {res, el in el.flatMap({ pel($0, res) }) })
    .map({ $0.dropLast(first.count) })
}

print(cartesianProduct([1, 2], [3, 4]))
print(cartesianProduct([3, 4], [1, 2]))
print(cartesianProduct([1, 2], []))
print(cartesianProduct([1776, 1789], [7, 12], [4, 14, 23], [0, 1]))
print(cartesianProduct([1, 2, 3], [30], [500, 100]))
print(cartesianProduct([1, 2, 3], [], [500, 100])


' FB 1.05.0 Win64

Function factorial(n As UInteger) As UInteger
  If n = 0 Then Return 1
  Return n * factorial(n - 1)
End Function

Function catalan1(n As UInteger) As UInteger
  Dim prod As UInteger = 1
  For i As UInteger = n + 2 To 2 * n
     prod *= i
  Next
  Return prod / factorial(n)
End Function

Function catalan2(n As UInteger) As UInteger
  If n = 0 Then Return 1
  Dim sum As UInteger = 0
  For i As UInteger = 0 To n - 1
    sum += catalan2(i) * catalan2(n - 1 - i)
  Next
  Return sum
End Function

Function catalan3(n As UInteger) As UInteger
  If n = 0 Then Return 1
  Return catalan3(n - 1) * 2 * (2 * n - 1) \ (n + 1)
End Function

Print "n", "First", "Second", "Third"
Print "-", "-----", "------", "-----"
Print
For i As UInteger = 0 To 15
  Print i,  catalan1(i), catalan2(i), catalan3(i)
Next
Print
Print "Press any key to quit"
Sleep


catalan[n] := binomial[2n,n]/(n+1)
for n = 0 to 15
   println[catalan[n]]


double add_n(double* a, double* b)
{
return *a + *b;
}


' FB 1.05.0 Win64

' Attempt to call Beep function in Win32 API
Dim As Any Ptr library = DyLibLoad("kernel32.dll") '' load dll

If library = 0 Then
  Print "Unable to load kernel32.dll - calling built in Beep function instead"
  Beep : Beep : Beep
Else
  Dim beep_ As Function (ByVal As ULong, ByVal As ULong) As Long  '' declare function pointer
  beep_ = DyLibSymbol(library, "Beep")
  If beep_ = 0 Then
    Print "Unable to retrieve Beep function from kernel32.dll - calling built in Beep function instead"
    Beep : Beep : Beep
  Else
    For i As Integer =  1 To 3 : beep_(1000, 250) : Next
  End If
  DyLibFree(library) '' unload library
End If

Print
Print "Press any key to quit"
Sleep


#include <stdio.h>
/* gcc -shared -fPIC -nostartfiles fakeimglib.c -o fakeimglib.so */
int openimage(const char *s)
{
    static int handle = 100;
    fprintf(stderr, "opening %s\n", s);
    return handle++;
}


proc cartesianProduct {l1 l2} {
  set result {}
  foreach el1 $l1 {
    foreach el2 $l2 {
      lappend result [list $el1 $el2]
    }
  }
  return $result
}

puts "simple"
puts "result: [cartesianProduct {1 2} {3 4}]"
puts "result: [cartesianProduct {3 4} {1 2}]"
puts "result: [cartesianProduct {1 2} {}]"
puts "result: [cartesianProduct {} {3 4}]"

proc cartesianNaryProduct {lists} {
  set result {{}}
  foreach l $lists {
    set res {}
    foreach comb $result {
      foreach el $l {
        lappend res [linsert $comb end $el]
      }
    }
    set result $res
  }
  return $result
}

puts "n-ary"
puts "result: [cartesianNaryProduct {{1776 1789} {7 12} {4 14 23} {0 1}}]"
puts "result: [cartesianNaryProduct {{1 2 3} {30} {500 100}}]"
puts "result: [cartesianNaryProduct {{1 2 3} {} {500 100}}]"


import integers.choose
import util.TextTable

def
  catalan( n ) = choose( 2n, n )/(n + 1)

  catalan2( n ) = product( (n + k)/k | k <- 2..n )

  catalan3( 0 ) = 1
  catalan3( n ) = 2*(2n - 1)/(n + 1)*catalan3( n - 1 )

t = TextTable()
t.header( 'n', 'definition', 'product', 'recursive' )
t.line()

for i <- 1..4
  t.rightAlignment( i )

for i <- 0..15
  t.row( i, catalan(i), catalan2(i), catalan3(i) )

println( t )


Catalan1 := n -> Binomial(2*n, n) - Binomial(2*n, n - 1);

Catalan2 := n -> Binomial(2*n, n)/(n + 1);

Catalan3 := function(n)
    local k, c;
    c := 1;
    k := 0;
    while k < n do
        k := k + 1;
        c := 2*(2*k - 1)*c/(k + 1);
    od;
    return c;
end;

Catalan4_memo := [1];
Catalan4 := function(n)
    if not IsBound(Catalan4_memo[n + 1]) then
        Catalan4_memo[n + 1] := Sum([0 .. n - 1], i -> Catalan4(i)*Catalan4(n - 1 - i));
    fi;
    return Catalan4_memo[n + 1];
end;

# The first fifteen: 0 to 14 !
List([0 .. 14], Catalan1);
List([0 .. 14], Catalan2);
List([0 .. 14], Catalan3);
List([0 .. 14], Catalan4);
# Same output for all four:
# [ 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440 ]


#!/usr/bin/env stack
-- stack --resolver lts-6.33 --install-ghc runghc --package unix

import Control.Exception ( try )
import Foreign ( FunPtr, allocaBytes )
import Foreign.C
    ( CSize(..), CString, withCAStringLen, peekCAStringLen )
import System.Info ( os )
import System.IO.Error ( ioeGetErrorString )
import System.IO.Unsafe ( unsafePerformIO )
import System.Posix.DynamicLinker
    ( RTLDFlags(RTLD_LAZY), dlsym, dlopen )

dlSuffix :: String
dlSuffix = if os == "darwin" then ".dylib" else ".so"

type RevFun = CString -> CString -> CSize -> IO ()

foreign import ccall "dynamic"
  mkFun :: FunPtr RevFun -> RevFun

callRevFun :: RevFun -> String -> String
callRevFun f s = unsafePerformIO $ withCAStringLen s $ \(cs, len) -> do
  allocaBytes len $ \buf -> do
    f buf cs (fromIntegral len)
    peekCAStringLen (buf, len)

getReverse :: IO (String -> String)
getReverse = do
  lib <- dlopen ("libcrypto" ++ dlSuffix) [RTLD_LAZY]
  fun <- dlsym lib "BUF_reverse"
  return $ callRevFun $ mkFun fun

main = do
  x <- try getReverse
  let (msg, rev) =
        case x of
          Left e -> (ioeGetErrorString e ++ "; using fallback", reverse)
          Right f -> ("Using BUF_reverse from OpenSSL", f)
  putStrLn msg
  putStrLn $ rev "a man a plan a canal panama"


require 'dll'
strdup=: 'msvcrt.dll _strdup >x *' cd <
free=: 'msvcrt.dll free n x' cd <
getstr=: free ] [email protected],&0 _1

DupStr=:verb define
  try.
    [email protected] y
  catch.
    y
  end.
)


Imports System.Runtime.CompilerServices

Module Module1

    <Extension()>
    Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T))
        Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)}
        Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item}))
    End Function

    Sub Main()
        Dim empty(-1) As Integer
        Dim list1 = {1, 2}
        Dim list2 = {3, 4}
        Dim list3 = {1776, 1789}
        Dim list4 = {7, 12}
        Dim list5 = {4, 14, 23}
        Dim list6 = {0, 1}
        Dim list7 = {1, 2, 3}
        Dim list8 = {30}
        Dim list9 = {500, 100}

        For Each sequnceList As Integer()() In {
            ({list1, list2}),
            ({list2, list1}),
            ({list1, empty}),
            ({empty, list1}),
            ({list3, list4, list5, list6}),
            ({list7, list8, list9}),
            ({list7, empty, list9})
        }
            Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $"({String.Join(", ", tuple)})")
            Console.WriteLine($"{{{String.Join(", ", cart)}}}")
        Next
    End Sub

End Module


package main

import (
    "fmt"
    "math/big"
)

func main() {
    var b, c big.Int
    for n := int64(0); n < 15; n++ {
        fmt.Println(c.Div(b.Binomial(n*2, n), c.SetInt64(n+1)))
    }
}


class Catalan
{
 public static void main(String[] args)
  {
    BigInteger N = 15;
    BigInteger k,n,num,den;
    BigInteger  catalan;
      print(1);
       for(n=2;n<=N;n++)
          {
            num = 1;
            den = 1;
              for(k=2;k<=n;k++)
                 {
                    num = num*(n+k);
                    den = den*k;
                    catalan = num/den;
                 }
            println(catalan);
          }

  }
}


/* TrySort.java */

import java.util.Collections;
import java.util.Random;

public class TrySort {
    static boolean useC;
    static {
	try {
	    System.loadLibrary("TrySort");
	    useC = true;
	} catch(UnsatisfiedLinkError e) {
	    useC = false;
	}
    }

    static native void sortInC(int[] ary);

    static class IntList extends java.util.AbstractList<Integer> {
	int[] ary;
	IntList(int[] ary) { this.ary = ary; }
	public Integer get(int i) { return ary[i]; }
	public Integer set(int i, Integer j) {
	    Integer o = ary[i]; ary[i] = j; return o;
	}
	public int size() { return ary.length; }
    }

    static class ReverseAbsCmp
	implements java.util.Comparator<Integer>
    {
	public int compare(Integer pa, Integer pb) {
	    /* Order from highest to lowest absolute value. */
	    int a = pa > 0 ? -pa : pa;
	    int b = pb > 0 ? -pb : pb;
	    return a < b ? -1 : a > b ? 1 : 0;
	}
    }

    static void sortInJava(int[] ary) {
	Collections.sort(new IntList(ary), new ReverseAbsCmp());
    }

    public static void main(String[] args) {
	/* Create an array of random integers. */
	int[] ary = new int[1000000];
	Random rng = new Random();
	for (int i = 0; i < ary.length; i++)
	    ary[i] = rng.nextInt();

	/* Do the reverse sort. */
	if (useC) {
	    System.out.print("Sorting in C...  ");
	    sortInC(ary);
	} else {
	    System.out.print
		("Missing library for C!  Sorting in Java...  ");
	    sortInJava(ary);
	}

	for (int i = 0; i < ary.length - 1; i++) {
	    int a = ary[i];
	    int b = ary[i + 1];
	    if ((a > 0 ? -a : a) > (b > 0 ? -b : b)) {
		System.out.println("*BUG IN SORT*");
		System.exit(1);
	    }
	}
	System.out.println("ok");
    }
}


import "/seq" for Lst

var prod2 = Fn.new { |l1, l2|
    var res = []
    for (e1 in l1) {
        for (e2 in l2) res.add([e1, e2])
    }
    return res
}

var prodN = Fn.new { |ll|
    if (ll.count < 2) Fiber.abort("There must be at least two lists.")
    var p2 = prod2.call(ll[0], ll[1])
    return ll.skip(2).reduce(p2) { |acc, l| prod2.call(acc, l) }.map { |l| Lst.flatten(l) }.toList
}

var printProdN = Fn.new { |ll|
    System.print("%(ll.join(" x ")) = ")
    System.write("[\n    ")
    System.print(prodN.call(ll).join("\n    "))
    System.print("]\n")
}

System.print("[1, 2] x [3, 4] = %(prodN.call([ [1, 2], [3, 4] ]))")
System.print("[3, 4] x [1, 2] = %(prodN.call([ [3, 4], [1, 2] ]))")
System.print("[1, 2] x []     = %(prodN.call([ [1, 2], [] ]))")
System.print("[]     x [1, 2] = %(prodN.call([ [], [1, 2] ]))")
System.print("[1, a] x [2, b] = %(prodN.call([ [1, "a"], [2, "b"] ]))")
System.print()
printProdN.call([ [1776, 1789], [7, 12], [4, 14, 23], [0, 1] ])
printProdN.call([ [1, 2, 3], [30], [500, 100] ])
printProdN.call([ [1, 2, 3], [], [500, 100] ])
printProdN.call([ [1, 2, 3], [30], ["a", "b"] ])


PROCEDURE Main()
   LOCAL i

   FOR i := 0 to 15
      ? PadL( i, 2 ) + ": " + hb_StrFormat("%d", Catalan( i ))
   NEXT

   RETURN

STATIC FUNCTION Catalan( n )
   LOCAL i, nCatalan := 1

   FOR i := 1 TO n
      nCatalan := nCatalan * 2 * (2 * i - 1) / (i + 1)
   NEXT

   RETURN nCatalan


-- Three infinite lists, corresponding to the three
-- definitions in the problem statement.

cats1 :: [Integer]
cats1 =
  (div . product . (enumFromTo . (2 +) <*> (2 *)))
    <*> (product . enumFromTo 1) <$> [0 ..]

cats2 :: [Integer]
cats2 =
  1 :
  fmap
    (\n -> sum (zipWith (*) (reverse (take n cats2)) cats2))
    [1 ..]

cats3 :: [Integer]
cats3 =
  scanl
    (\c n -> c * 2 * (2 * n - 1) `div` succ n)
    1
    [1 ..]

main :: IO ()
main = mapM_ (print . take 15) [cats1, cats2, cats3]


#this example works on Windows
ccall( (:GetDoubleClickTime, "User32"), stdcall,
	Uint, (), )

ccall( (:clock, "libc"), Int32, ())


-- calculate CRC-32 checksum
str = "The quick brown fox jumps over the lazy dog"

-- is shared library (in Director called "Xtra", a DLL in windows, a sharedLib in
-- OS X) available?
if ilk(xtra("Crypto"))=#xtra then

  -- use shared library
  cx = xtra("Crypto").new()
  crc = cx.cx_crc32_string(str)

else

  -- otherwise use (slower) pure lingo solution
  crcObj = script("CRC").new()
  crc = crcObj.crc32(str)

end if


procedure main()
every writes(catalan(0 to 14)," ")
end

procedure catalan(n) # return catalan(n) or fail
static M
initial M := table()
n=0 & return 1

if n > 0 then
   return (n = 1) | \M[n] | ( M[n] := (2*(2*n-1)*catalan(n-1))/(n+1))
end


alien = require("alien")
msgbox = alien.User32.MessageBoxA
msgbox:types({ ret='long', abi='stdcall', 'long', 'string', 'string', 'long' })
retval = msgbox(0, 'Please press Yes, No or Cancel', 'The Title', 3)
print(retval) --> 6, 7 or 2


> cfloor := define_external( floor, s::float[8], RETURN::float[8], LIB = "libm.so" ):
> cfloor( 2.3 );
                                   2.


Needs["NETLink`"];
externalFloor = DefineDLLFunction["floor", "msvcrt.dll", "double", { "double" }];
externalFloor[4.2]
-> 4.


proc openimage(s: cstring): cint {.importc, dynlib: "./fakeimglib.so".}

echo openimage("foo")
echo openimage("bar")
echo openimage("baz")


import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CatlanNumbers {

    public static void main(String[] args) {
        Catlan f1 = new Catlan1();
        Catlan f2 = new Catlan2();
        Catlan f3 = new Catlan3();
        System.out.printf("           Formula 1     Formula 2     Formula 3%n");
        for ( int n = 0 ; n <= 15 ; n++ ) {
             System.out.printf("C(%2d) = %,12d  %,12d  %,12d%n", n, f1.catlin(n), f2.catlin(n), f3.catlin(n));
        }
    }

    private static interface Catlan {
        public BigInteger catlin(long n);
    }

    private static class Catlan1 implements Catlan {

        //  C(n) = (2n)! / (n+1)!n!
        @Override
        public BigInteger catlin(long n) {
            List<Long> numerator = new ArrayList<>();
            for ( long k = n+2 ; k <= 2*n ; k++ ) {
                numerator.add(k);
            }

            List<Long> denominator = new ArrayList<>();
            for ( long k = 2 ; k <= n ; k++ ) {
                denominator.add(k);
            }

            for ( int i = numerator.size()-1 ; i >= 0  ; i-- ) {
                for ( int j = denominator.size()-1 ; j >= 0  ; j-- ) {
                    if ( denominator.get(j) == 1 ) {
                        continue;
                    }
                    if ( numerator.get(i) % denominator.get(j) == 0 ) {
                        long val = numerator.get(i) / denominator.get(j);
                        numerator.set(i, val);
                        denominator.remove(denominator.get(j));
                        if ( val == 1 ) {
                            break;
                        }
                    }
                }
            }

            BigInteger catlin = BigInteger.ONE;
            for ( int i = 0 ; i < numerator.size() ; i++ ) {
                catlin = catlin.multiply(BigInteger.valueOf(numerator.get(i)));
            }
            for ( int i = 0 ; i < denominator.size() ; i++ ) {
                catlin = catlin.divide(BigInteger.valueOf(denominator.get(i)));
            }
            return catlin;
        }
    }

    private static class Catlan2 implements Catlan {

        private static Map<Long,BigInteger> CACHE = new HashMap<>();
        static {
            CACHE.put(0L, BigInteger.ONE);
        }

        //  C(0) = 1, C(n+1) = sum(i=0..n,C(i)*C(n-i))
        @Override
        public BigInteger catlin(long n) {
            if ( CACHE.containsKey(n) ) {
                return CACHE.get(n);
            }
            BigInteger catlin = BigInteger.ZERO;
            n--;
            for ( int i = 0 ; i <= n ; i++ ) {
                //System.out.println("n = " + n + ", i = " + i + ", n-i = " + (n-i));
                catlin = catlin.add(catlin(i).multiply(catlin(n-i)));
            }
            CACHE.put(n+1, catlin);
            return catlin;
        }
    }

    private static class Catlan3 implements Catlan {

        private static Map<Long,BigInteger> CACHE = new HashMap<>();
        static {
            CACHE.put(0L, BigInteger.ONE);
        }

        //  C(0) = 1, C(n+1) = 2*(2n-1)*C(n-1)/(n+1)
        @Override
        public BigInteger catlin(long n) {
            if ( CACHE.containsKey(n) ) {
                return CACHE.get(n);
            }
            BigInteger catlin = BigInteger.valueOf(2).multiply(BigInteger.valueOf(2*n-1)).multiply(catlin(n-1)).divide(BigInteger.valueOf(n+1));
            CACHE.put(n, catlin);
            return catlin;
        }
    }

}


open Dlffi

let get_int = function Int v -> v | _ -> failwith "get_int"
let get_ptr = function Ptr v -> v | _ -> failwith "get_ptr"
let get_float = function Float v -> v | _ -> failwith "get_float"
let get_double = function Double v -> v | _ -> failwith "get_double"
let get_string = function String v -> v | _ -> failwith "get_string"

let () =
  (* load the library *)
  let xlib = dlopen "/usr/lib/libX11.so" [RTLD_LAZY] in
  (* load the functions *)
  let _open_display = dlsym xlib "XOpenDisplay"
  and _default_screen = dlsym xlib "XDefaultScreen"
  and _display_width = dlsym xlib  "XDisplayWidth"
  and _display_height = dlsym xlib "XDisplayHeight"
  in
  (* wrap functions to provide a higher level interface *)
  let open_display ~name = get_ptr(fficall _open_display [| String name |] Return_ptr)
  and default_screen ~dpy = get_int(fficall _default_screen [| (Ptr dpy) |] Return_int)
  and display_width ~dpy ~scr = get_int(fficall _display_width [| (Ptr dpy); (Int scr) |] Return_int)
  and display_height ~dpy ~scr = get_int(fficall _display_height [| (Ptr dpy); (Int scr) |] Return_int)
  in
  (* use our functions *)
  let dpy = open_display ~name:":0" in
  let screen_number = default_screen ~dpy in
  let width = display_width ~dpy ~scr:screen_number
  and height = display_height ~dpy ~scr:screen_number in
  Printf.printf "# Screen dimensions are: %d x %d pixels\n" width height;
  dlclose xlib;
;;


(import (otus ffi))

(define self (load-dynamic-library #f))
(define strdup
   (self type-string "strdup" type-string))

(print (strdup "Hello World!"))


'Loading a shared library at run time and calling a function.

declare MessageBox(sys hWnd, String text,caption, sys utype)

sys user32 = LoadLibrary "user32.dll"

if user32 then @Messagebox = getProcAddress user32,"MessageBoxA"

if @MessageBox then MessageBox 0,"Hello","OxygenBasic",0

'...

FreeLibrary user32


use Inline
    C => "DATA",
    ENABLE => "AUTOWRAP",
    LIBS => "-lm";

print 4*atan(1) . "\n";

__DATA__
__C__
double atan(double x);


def catalan:
  if . == 0 then 1
  elif . < 0 then error("catalan is not defined on \(.)")
  else (2 * (2*. - 1) * ((. - 1) | catalan)) / (. + 1)
  end;


catalannum(n::Integer) = binomial(2n, n) ÷ (n + 1)

@show catalannum.(1:15)
@show catalannum(big(100))


without js -- not from a browser, mate!
string {libname,funcname} = iff(platform()=WINDOWS?{"user32","CharLowerA"}:{"libc","tolower"})
atom lib = open_dll(libname)
integer func = define_c_func(lib,funcname,{C_INT},C_INT)
if func=-1 then
    ?{{lower('A')}} -- (you don't //have// to crash!)
else
    ?c_func(func,{'A'}) -- ('A'==65)
end if


(load "@lib/gcc.l")

(gcc "x11" '("-lX11") 'xOpenDisplay 'xCloseDisplay)

#include <X11/Xlib.h>

any xOpenDisplay(any ex) {
   any x = evSym(cdr(ex));    // Get display name
   char display[bufSize(x)];  // Create a buffer for the name

   bufString(x, display);     // Upack the name
   return boxCnt((long)XOpenDisplay(display));
}

any xCloseDisplay(any ex) {
   return boxCnt(XCloseDisplay((Display*)evCnt(ex, cdr(ex))));
}
/**/

# With that we can open and close the display:
: (setq Display (xOpenDisplay ":0.7"))   # Wrong
-> 0
: (setq Display (xOpenDisplay ":0.0"))   # Correct
-> 158094320
: (xCloseDisplay Display)
-> 0


#INCLUDE "Win32API.inc"

FUNCTION PBMAIN () AS LONG
    DIM hWnd AS LONG
    DIM msg AS ASCIIZ * 14, titl AS ASCIIZ * 8

    hWnd = LoadLibrary ("user32")
    msg = "Hello, world!"
    titl = "Example"
    IF ISTRUE (hWnd) THEN
        funcAddr& = GetProcAddress (hWnd, "MessageBoxA")
        IF ISTRUE (funcAddr&) THEN
            ASM push 0&
            tAdr& = VARPTR(titl)
            ASM push tAdr&
            mAdr& = VARPTR(msg)
            ASM push mAdr&
            ASM push 0&
            CALL DWORD funcAddr&
        ELSE
            GOTO epicFail
        END IF
    ELSE
        GOTO epicFail
    END IF

    GOTO getMeOuttaHere

epicFail:
    MSGBOX msg, , titl

getMeOuttaHere:
    IF ISTRUE(hWnd) THEN
        tmp& = FreeLibrary (hWnd)
        IF ISFALSE(tmp&) THEN MSGBOX "Error freeing library... [shrug]"
    END IF
END FUNCTION


if OpenLibrary(0, "USER32.DLL")
  *MessageBox = GetFunction(0, "MessageBoxA")
  CallFunctionFast(*MessageBox, 0, "Body", "Title", 0)
  CloseLibrary(0)
endif


abstract class Catalan {
    abstract operator fun invoke(n: Int) : Double

    protected val m = mutableMapOf(0 to 1.0)
}

object CatalanI : Catalan() {
    override fun invoke(n: Int): Double {
        if (n !in m)
            m[n] = Math.round(fact(2 * n) / (fact(n + 1) * fact(n))).toDouble()
        return m[n]!!
    }

    private fun fact(n: Int): Double {
        if (n in facts)
            return facts[n]!!
        val f = n * fact(n -1)
        facts[n] = f
        return f
    }

    private val facts = mutableMapOf(0 to 1.0, 1 to 1.0, 2 to 2.0)
}

object CatalanR1 : Catalan() {
    override fun invoke(n: Int): Double {
        if (n in m)
            return m[n]!!

        var sum = 0.0
        for (i in 0..n - 1)
            sum += invoke(i) * invoke(n - 1 - i)
        sum = Math.round(sum).toDouble()
        m[n] = sum
        return sum
    }
}

object CatalanR2 : Catalan() {
    override fun invoke(n: Int): Double {
        if (n !in m)
            m[n] = Math.round(2.0 * (2 * (n - 1) + 1) / (n + 1) * invoke(n - 1)).toDouble()
        return m[n]!!
    }
}

fun main(args: Array<String>) {
    val c = arrayOf(CatalanI, CatalanR1, CatalanR2)
    for(i in 0..15) {
        c.forEach { print("%9d".format(it(i).toLong())) }
        println()
    }
}


import ctypes

user32_dll = ctypes.cdll.LoadLibrary('User32.dll')
print user32_dll.GetDoubleClickTime()


Declare Dynamic Library "Kernel32"
    Sub SetLastError (ByVal dwErr As Long)
    Function GetLastError& ()
End Declare

SetLastError 20
Print GetLastError


dyn.load("my/special/R/lib.so")
.Call("my_lib_fun", arg1, arg2)


#lang racket
(require ffi/unsafe)
(define libm (ffi-lib "libm")) ; get a handle for the C math library
; look up sqrt in the math library. if we can't find it, return the builtin sqrt
(define extern-sqrt (get-ffi-obj 'sqrt libm (_fun _double -> _double)
                                 (lambda () sqrt)))


use NativeCall;

sub XOpenDisplay(Str $s --> int64) is native('X11') {*}
sub XCloseDisplay(int64 $i --> int32) is native('X11') {*}

if try my $d = XOpenDisplay ":0.0" {
    say "ID = $d";
    XCloseDisplay($d);
}
else {
    say "No X11 library!";
    say "Use this window instead --> ⬜";
}


val .factorial = f if(.x < 2: 1; .x x self(.x - 1))
val .catalan = f(.n) .factorial(2 x .n) / .factorial(.n+1) / .factorial(.n)

for .i in 0..15 {
    writeln $"\.i:2;: \(.catalan(.i):10)"
}

writeln "10000: ", .catalan(10000)


print "non-recursive version"
print catNonRec(5)
for i = 0 to 15
    print i;"   =   "; catNonRec(i)
next
print

print "recursive version"
print catRec(5)
for i = 0 to 15
    print i;"   =   "; catRec(i)
next
print

print "recursive with memoisation"
redim cats(20)  'clear the array
print catRecMemo(5)
for i = 0 to 15
    print i;"   =   "; catRecMemo(i)
next
print

wait

function catNonRec(n)   'non-recursive version
    catNonRec=1
    for i=1 to n
        catNonRec=((2*((2*i)-1))/(i+1))*catNonRec
    next
end function

function catRec(n)  'recursive version
    if n=0 then
        catRec=1
    else
        catRec=((2*((2*n)-1))/(n+1))*catRec(n-1)
    end if
end function

function catRecMemo(n)  'recursive version with memoisation
    if n=0 then
        catRecMemo=1
    else
        if cats(n-1)=0 then    'call it recursively only if not already calculated
            prev = catRecMemo(n-1)
        else
            prev = cats(n-1)
        end if
        catRecMemo=((2*((2*n)-1))/(n+1))*prev
    end if
    cats(n) = catRecMemo    'memoisation for future use
end function


/*REXX program calls a function  (sysTextScreenSize)  in a shared library  (regUtil).   */

                        /*Note:  the  REGUTIL.DLL  (REGina UTILity Dynamic Link Library */
                        /*       should be in the  PATH  or the current directory.      */

rca= rxFuncAdd('sysLoadFuncs', "regUtil", 'sysLoadFuncs')  /*add a function library.    */
if rca\==0  then do                                        /*examine the    return code.*/
                 say 'return code' rca "from rxFuncAdd"    /*tell about bad    "     "  */
                 exit rca                                  /*exit this program with RC. */
                 end

rcl= sysLoadFuncs()                                        /*we can load the functions. */
if rcl\==0  then do                                        /*examine the    return code.*/
                 say 'return code' rcl "from sysLoadFuncs" /*tell about bad    "     "  */
                 exit rcl                                  /*exit this program with RC. */
                 end
                                                           /* [↓]   call a function.    */
$= sysTextScreenSize()                                     /*$  has 2 words:  rows cols */
parse var  $     rows  cols  .                             /*get two numeric words in $.*/
say '    rows='  rows                                      /*show number of screen rows.*/
say '    cols='  cols                                      /*  "     "    "     "  cols.*/

rcd= SysDropFuncs()                                        /*make functions inaccessible*/
if rcd\==0  then do                                        /*examine the    return code.*/
                 say 'return code' rcd "from sysDropFuncs" /*tell about bad    "     "  */
                 exit rcd                                  /*exit this program with RC. */
                 end
exit 0                                           /*stick a fork in it,  we're all done. */


require 'fiddle/import'

module FakeImgLib
  extend Fiddle::Importer
  begin
    dlload './fakeimglib.so'
    extern 'int openimage(const char *)'
  rescue Fiddle::DLError
    # Either fakeimglib or openimage() is missing.
    @@handle = -1
    def openimage(path)
      $stderr.puts "internal openimage opens #{path}\n"
      @@handle += 1
    end
    module_function :openimage
  end
end

handle = FakeImgLib.openimage("path/to/image")
puts "opened with handle #{handle}"


#![allow(unused_unsafe)]
extern crate libc;

use std::io::{self,Write};
use std::{mem,ffi,process};

use libc::{c_double, RTLD_NOW};

// Small macro which wraps turning a string-literal into a c-string.
// This is always safe to call, and the resulting pointer has 'static lifetime
macro_rules! to_cstr {
    ($s:expr) => {unsafe {ffi::CStr::from_bytes_with_nul_unchecked(concat!($s, "\0").as_bytes()).as_ptr()}}
}

macro_rules! from_cstr {
    ($p:expr) => {ffi::CStr::from_ptr($p).to_string_lossy().as_ref() }
}

fn main() {
    unsafe {
        let handle = libc::dlopen(to_cstr!("libm.so.6"), RTLD_NOW);

        if handle.is_null() {
            writeln!(&mut io::stderr(), "{}", from_cstr!(libc::dlerror())).unwrap();
            process::exit(1);
        }

        let extern_cos = libc::dlsym(handle, to_cstr!("cos"))
                .as_ref()
                .map(mem::transmute::<_,fn (c_double) -> c_double)
                .unwrap_or(builtin_cos);
        println!("{}", extern_cos(4.0));
    }
}

fn builtin_cos(x: c_double) -> c_double {
    x.cos()
}


to factorial :n
  output ifelse [less? :n 1] 1 [product :n factorial difference :n 1]
end
to choose :n :r
  output quotient factorial :n product factorial :r factorial difference :n :r
end
to catalan :n
  output product (quotient sum :n 1) choose product 2 :n :n
end

repeat 15 [print catalan repcount]


-- recursive with memoization
catalan = {[0] = 1}
setmetatable(catalan, {
	__index = function(c, n)
			c[n] = c[n-1]*2*(2*n-1)/(n+1)
			return c[n]
		end
	}
)

for i=0,14 do
	print(catalan[i])
end


            NORMAL MODE IS INTEGER
            DIMENSION C(15)

            C(0) = 1
            THROUGH CALC, FOR N=1, 1, N.GE.15
CALC        C(N) = ((4*N-2)*C(N-1))/(N+1)

            THROUGH SHOW, FOR N=0, 1, N.GE.15
SHOW        PRINT FORMAT CFMT,N,C(N)

            VECTOR VALUES CFMT=$2HC(,I2,4H) = ,I7*$
            END OF PROGRAM


import net.java.dev.sna.SNA
import com.sun.jna.ptr.IntByReference

object GetDiskFreeSpace extends App with SNA {

  snaLibrary = "Kernel32" // Native library name
/*
 * Important Note!
 *
 * The val holding the SNA-returned function must have the same name as the native function itself
 * (see line following this comment). This is the only place you specify the native function name.
 */
  val GetDiskFreeSpaceA = SNA[String, IntByReference, IntByReference, IntByReference, IntByReference, Boolean]

  // This Windows function is described here:
  //     http://msdn.microsoft.com/en-us/library/aa364935(v=vs.85).aspx
  val (disk, spc, bps, fc, tc) = ("C:\\",
    new IntByReference, // Sectors per cluster
    new IntByReference, // Bytes per sector
    new IntByReference, // Free clusters
    new IntByReference) // Total clusters

  val ok = GetDiskFreeSpaceA(disk, spc, bps, fc, tc) // status
  println(f"'$disk%s' ($ok%s): sectors/cluster: ${spc.getValue}%d,  bytes/sector: ${bps.getValue}%d, " +
    f" free-clusters: ${fc.getValue}%d,  total/clusters: ${tc.getValue}%d%n")
}}


DLD addLibrary: 'fakeimglib'.

Object subclass: ExtLib [
  ExtLib class >> openimage: aString [
    (CFunctionDescriptor isFunction: 'openimage')
    ifTrue: [
       (CFunctionDescriptor for: 'openimage'
                            returning: #int
                            withArgs: #( #string ) ) callInto: (ValueHolder null).
    ] ifFalse: [ ('internal open image %1' % { aString }) displayNl ]
  ]
].

ExtLib openimage: 'test.png'.


-INCLUDE 'ffi.sno'

    ffi_m = FFI_DLOPEN('/usr/lib/x86_64-linux-gnu/libm.so')
    ffi_m_hypot = FFI_DLSYM(ffi_m, 'hypot')
    DEFINE_FFI('hypot(double,double)double', ffi_m_hypot)

    OUTPUT = hypot(1,2)
    OUTPUT = hypot(2,3)
    OUTPUT = hypot(3,4)
    OUTPUT = hypot(4,5)

END


CatalanNumbers := proc( n::posint )
    return seq( (2*i)!/((i + 1)!*i!), i = 0 .. n - 1 );
end proc:
CatalanNumbers(15);


function n = catalanNumber(n)
    for i = (1:length(n))
        n(i) = (1/(n(i)+1))*nchoosek(2*n(i),n(i));
    end
end