with javascript_semantics
if name="Pete" then
  -- do something
elsif age>50 then
  -- do something
elsif age<20 then
  -- do something
else
  -- do something
end if


var a = 5;
if (a == 5) {
   doSomething();
} else if (a > 0) {
   doSomethingElse();
} else {
   error();
}


<?php

$foo = 3;

if ($foo == 2)
  //do something

if ($foo == 3)
  //do something
else
  //do something else

if ($foo != 0)
{
  //do something
}
else
{
  //do another thing
}

?>


go =>
  N = 10,

  % "direct" test that will fail if not satisfied
  N < 14,

  % if/then/elseif/else
  if N < 14 then
    println("less than 14")
  elseif N == 14 then
    println("is 14")
  else
    println("not less than 14")
  end,

  % From Prolog: (condition -> then ; else)
  ( N < 14 ->
   println("less than 14")
   ;
   println("not less than 14")
  ),

  % Ret = cond(condition, then, else)
  println(cond(N < 14, "less than 14", "not less than 14")),

  % as a predicate
  test_pred(N),

  % as condition in a function's head
  println(test_func(N)),

  println(ok), % all tests are ok

  nl.

% as a predicate
test_pred(N) ?=>
  N < 14,
  println("less than 14").
test_pred(N) =>
  N >= 14,
  println("not less than 14").

% condition in function head
test_func(N) = "less than 14", N < 14 => true.
test_func(_N) = "not less than 14" => true.


%!PS-Adobe-3.0
%%BoundingBox: 0 0 400 400

/size 400 def

realtime srand
/rand1 { rand 2147483647 div } def

/m { moveto } bind def
/l { rlineto} bind def
/drawboard {
        0 1 n 1 sub { /y exch def
        0 1 n 1 sub { /x exch def
                board x get y get 1 eq {
                        x c mul y c mul m
                        c 0 l 0 c l c neg 0 l
                        closepath fill
                } if
        } for } for
} def

/r1n { dup 0 lt { n add } if dup n ge { n sub } if } def
/neighbors { /y exch def /x exch def 0
        y 1 sub 1 y 1 add { r1n /y1 exch def
        x 1 sub 1 x 1 add { r1n /x1 exch def
                board x1 get y1 get add
        } for } for
        board x get y get sub
} def

/iter {
        /board
        [0 1 n 1 sub { /x exch def
        [0 1 n 1 sub { /y exch def
                x y neighbors
                board x get y get
                0 eq    { 3 eq {1}{0} ifelse }
                        { dup 2 eq exch 3 eq or {1}{0} ifelse } ifelse
        } for ]
        } for ] def
} def

/n 200 def
/initprob .15 def
/c size n div def
/board [ n {[ n { rand1 initprob le {1}{0} ifelse } repeat]} repeat ] def

1000 { drawboard showpage iter } repeat
%%EOF


(if (condition)                  # If the condition evaluates to non-NIL
   (then-do-this)                # Then execute the following expression
   (else-do-that)                # Else execute all other expressions
   (and-more) )

(ifn (condition)                 # If the condition evaluates to NIL
   (then-do-this)                # Then execute the following expression
   (else-do-that)                # Else execute all other expressions
   (and-more) )


if condition_exp then unique_statement; else unique_statement;

if condition_exp then
    unique_statement;
else
    unique_statement;

if condition_exp
then do;
    list_of_statements;
end;
else do;
    list_of_statements;
end;


%----------------------------------------------------------------------%
% GAME OF LIFE                                                         %
%                                                                      %
% Adapt the prediacte grid_size according to the grid size of the      %
%   start pic.                                                         %
% Modify the number of generations.                                    %
% Run PROLOG and type '[gol].' to compile the source file.             %
% Create a subfolder <subfolder> where your gol.pl resides and place   %
%   your initial PBM '<filename>0.0000.pbm' inside <subfolder>.        %
% You need to adjust the number of zeros after <filename>. The         %
%   sequence of zeros after '0.' must be as long as the number of      %
%   generations. This is important to obtain a propper animation.      %
%   (Maybe someone knows a better solution for this)                   %
% Start PROLOG and run                                                 %
%                                                                      %
%                cellular('./<subloder>/<filename>').                  %
%                                                                      %
% Inside <subfolder> run the following shell command                   %
%                                                                      %
%         convert -delay 25 -loop 0 <filename>* <filename>.gif         %
%                                                                      %
%----------------------------------------------------------------------%

%----------------------------------------------------------------------%
% Special thanks to René Thiemann improving the runtime performance.   %
%----------------------------------------------------------------------%

% Size of the 2D grid
grid_size(300).
% Number of generations
generations(1000).

%----------------------------------------------------------------------%
% Main procedure: generate n generations of life and store each file.  %
%   cellular( +File path )                                             %
%----------------------------------------------------------------------%
cellular(I) :-
	grid_size(GS),
	string_concat(I,'0.0000.pbm',I1),
	read_pbm(I1,GS,M),
	cellular_(I,M,GS,1), !.

cellular_(I,M,GS,N) :-
	N1 is N+1,
	format(atom(N0),'~4d',N),
	string_concat(I,N0,I1),
	string_concat(I1,'.pbm',I2),
	step(M,M1),
	write_pbm(M1,GS,I2), !,
	cellular_(I,M1,GS,N1).
cellular_(_,_,_,GE) :-
	generations(GE),!.

%----------------------------------------------------------------------%
% Apply the Game Of Life rule set to every cell.                       %
%   step( +OldMatrix, +NewMatrix )                                     %
%                                                                      %
%  ss | s | ... | s       ss ... step_ss                               %
% ----+---+-----+---      s  ... step_s                                %
%  ii | i | ... | i       ii ... step_ii                               %
% ----+---+-----+---      i  ... step_i                                %
%   : | : |  :  | :       ee ... step_ee                               %
% ----+---+-----+---      e  ... step_e                                %
%  ii | i | ... | i                                                    %
% ----+---+-----+---                                                   %
%  ee | e | ... | e                                                    %
%                                                                      %
%----------------------------------------------------------------------%
step([R1,R2|M],[H|T]) :-
	step_ss(R1,R2,H), !,
	step_([R1,R2|M],T).

step_([R1,R2,R3|M],[H|T]) :-
	step_ii(R1,R2,R3,H),
	step_([R2,R3|M],T), !.
step_([R1,R2],[H]) :-
	step_ee(R1,R2,H).

% Start case
step_ss([A1,A2|R1],[B1,B2|R2],[H|T]) :-
	rule([0,0,0],[0,A1,A2],[0,B1,B2],H),
	step_s([A1,A2|R1],[B1,B2|R2],T).
step_s([A1,A2,A3|R1],[B1,B2,B3|R2],[H|T]) :-
	rule([0,0,0],[A1,A2,A3],[B1,B2,B3],H),
	step_s([A2,A3|R1],[B2,B3|R2],T).
step_s([A1,A2],[B1,B2],[H]) :-
	rule([0,0,0],[A1,A2,0],[B1,B2,0],H).

% Immediate case
step_ii([A1,A2|R1],[B1,B2|R2],[C1,C2|R3],[H|T]) :-
	rule([0,A1,A2],[0,B1,B2],[0,C1,C2],H),
	step_i([A1,A2|R1],[B1,B2|R2],[C1,C2|R3],T).
step_i([A1,A2,A3|R1],[B1,B2,B3|R2],[C1,C2,C3|R3],[H|T]) :-
	rule([A1,A2,A3],[B1,B2,B3],[C1,C2,C3],H),
	step_i([A2,A3|R1],[B2,B3|R2],[C2,C3|R3],T).
step_i([A1,A2],[B1,B2],[C1,C2],[H]) :-
	rule([A1,A2,0],[B1,B2,0],[C1,C2,0],H).

% End case
step_ee([A1,A2|R1],[B1,B2|R2],[H|T]) :-
	rule([0,A1,A2],[0,B1,B2],[0,0,0],H),
	step_e([A1,A2|R1],[B1,B2|R2],T).
step_e([A1,A2,A3|R1],[B1,B2,B3|R2],[H|T]) :-
	rule([A1,A2,A3],[B1,B2,B3],[0,0,0],H),
	step_e([A2,A3|R1],[B2,B3|R2],T).
step_e([A1,A2],[B1,B2],[H]) :-
	rule([A1,A2,0],[B1,B2,0],[0,0,0],H).

%----------------------------------------------------------------------%
% o Any dead cell with exactly three live neighbours becomes a live    %
%   cell, as if by reproduction.                                       %
% o Any other dead cell remains dead.                                  %
% o Any live cell with fewer than two live neighbours dies, as if      %
%   caused by under-population.                                        %
% o Any live cell with two or three live neighbours lives on to the    %
%   next generation.                                                   %
% o Any live cell with more than three live neighbours dies, as if by  %
%   overcrowding.                                                      %
%                                                                      %
% [Source: Wikipedia]                                                  %
%----------------------------------------------------------------------%
rule([A,B,C],[D,0,F],[G,H,I],1) :- A+B+C+D+F+G+H+I =:= 3.
rule([_,_,_],[_,0,_],[_,_,_],0).
rule([A,B,C],[D,1,F],[G,H,I],0) :- A+B+C+D+F+G+H+I < 2.
rule([A,B,C],[D,1,F],[G,H,I],1) :- A+B+C+D+F+G+H+I =:= 2.
rule([A,B,C],[D,1,F],[G,H,I],1) :- A+B+C+D+F+G+H+I =:= 3.
rule([A,B,C],[D,1,F],[G,H,I],0) :- A+B+C+D+F+G+H+I > 3.

%----------------------------------------------------------------------%
% Read a 2bit Protable Bitmap into a GS x GS 2-dimensional list.       %
%   read_pbm( +File path, +Grid size, -List 2D )                       %
%----------------------------------------------------------------------%
read_pbm(F,GS,M) :-
	open(F,read,S),
	skip(S,10),
	skip(S,10),
	get(S,C),
	read_file(S,C,L),
	nest(L,GS,M),
	close(S).

read_file(S,C,[CHR|T]) :-
	CHR is C-48,
	get(S,NC),
	read_file(S,NC,T).
read_file(_,-1,[]) :- !.

%----------------------------------------------------------------------%
% Morph simple list into a 2-dimensional one with size GS x GS         %
%   nest( ?List simple, ?Grid size, ?2D list )                         %
%----------------------------------------------------------------------%
nest(L,GS,[H|T]) :-
	length(H,GS),
	append(H,S,L),
	nest(S,GS,T).
nest(L,GS,[L]) :-
	length(L,S),
	S =< GS, !.

%----------------------------------------------------------------------%
% Write a GS x GS 2-dimensional list into a 2bit Protable Bitmap.      %
%   write_pbm( +List 2D, +Grid size, +File path )                      %
%----------------------------------------------------------------------%
write_pbm(L,GS,F) :-
	open(F,write,S),
	write(S,'P1'), nl(S),
	write(S,GS), put(S,' '), write(S,GS), nl(S),
	write_file(S,L),
	close(S).

write_file(S,[H|T]) :-
	write_line(S,H), nl(S),
	write_file(S,T).
write_file(_,[]) :- !.

write_line(S,[H|T]) :-
	write(S,H), put(S,' '),
	write_line(S,T).
write_line(_,[]) :- !.


/* IF-THEN-ELSE - THE ELSE STATEMENT; PART IS OPTIONAL */
IF COND THEN STATEMENT1; ELSE STATEMENT2;

/* CAN BE CHAINED - THE ELSE STATEMENTX; PART IS STILL OPTIONAL */
IF      COND1 THEN STATEMENT1;
ELSE IF CONB2 THEN STATEMENT2;
ELSE IF CONB3 THEN STATEMENT3;
ELSE               STATEMENTX;


boolean play = true;
int cellSize = 10;
int cols, rows;
int lastCell = 0;
int sample = 10;
// Game of life board
int[][] grid;

void setup() {
  size(800, 500);
  noStroke();
  // Calculate cols, rows and init array
  cols = width/cellSize;
  rows = height/cellSize;
  grid = new int[cols][rows];
  init(-1); // randomized start

  println("Press 'space' to start/stop");
  println("'e' to clear all cells");
  println("'b' demonstrate 'blinker'");
  println("'g' demonstrate glider");
  println("'r' to randomize grid");
  println("'+'  and '-' to change speed");

}

void draw() {
  background(0);

  for ( int i = 0; i < cols; i++) {
    for ( int j = 0; j < rows; j++) {
      if ((grid[i][j] == 1)) fill(255);
      else fill(0);
      rect(i*cellSize, j*cellSize, cellSize, cellSize);
    }
  }
  if (play && frameCount%sample==0 && !mousePressed) {
    generate();
  }
}

void generate() {
  int[][] nextGrid = new int[cols][rows];
  for (int x = 0; x < cols; x++) {
    for (int y = 0; y < rows; y++) {
      int ngbs = countNgbs(x, y);
      // the classic Conway rules
      if      ((grid[x][y] == 1) && (ngbs <  2)) nextGrid[x][y] = 0; // solitude
      else if ((grid[x][y] == 1) && (ngbs >  3)) nextGrid[x][y] = 0; // crowded
      else if ((grid[x][y] == 0) && (ngbs == 3)) nextGrid[x][y] = 1; // cell born
      else                              nextGrid[x][y] = grid[x][y]; // keep
    }
  }
  grid = nextGrid;
}

int countNgbs(int x, int y) {
  int ngbCount = 0;
  for (int i = -1; i <= 1; i++) {
    for (int j = -1; j <= 1; j++) {
      // 'united' borders
      ngbCount += grid[(x+i+cols)%cols][(y+j+rows)%rows];
    }
  }
  // cell taken out of count
  ngbCount -= grid[x][y];
  return ngbCount;
}

void init(int option) {
  int state;
  for (int x = 0; x < cols; x++) {
    for (int y = 0; y < rows; y++) {
      if (option == -1) {
        state = int(random(2));
      } else {
        state = option;
      }
      grid[x][y] = state;
    }
  }
}

void keyReleased() {
  if (key == 'r') {
    init(-1); // randomize grid
  }
  if (key == 'e') {
    init(0); // empty grid
  }
  if (key == 'g') {
    int glider[][] = {
      {0, 1, 0},
      {0, 0, 1},
      {1, 1, 1}};
    setNine(10, 10, glider);
  }
  if (key == 'b') {
    int blinker[][] = {
      {0, 1, 0},
      {0, 1, 0},
      {0, 1, 0}};
    setNine(10, 10, blinker);
  }
  if (key == ' ') {
    play = !play;
  }
  if (key == '+' || key == '=') {
    sample=max(sample-1, 1);
  }
  if (key == '-') {
    sample++;
  }
}

void setNine(int x, int y, int nine[][]) {
  for (int i = 0; i <= 2; i++) {
    for (int j = 0; j <= 2; j++) {
      grid[(x+i+cols)%cols][(y+j+rows)%rows] = nine[i][j];
    }
  }
}

void mousePressed() {
  paint();
}
void mouseDragged() {
  paint();
}

void paint() {
  int x = mouseX/cellSize;
  int y = mouseY/cellSize;
  int p = y*cols + x;
  if (p!=lastCell) {
    lastCell=p;
    int states[] = {1, 0};
    grid[x][y] = states[grid[x][y]]; // invert
  }
}


# standard if
if (condition) {
    # ...
}

# if-then-else
if (condition) {
    # ...
} else {
    # ...
}

# if-then-elseif-else
if (condition) {
    # ...
} elseif (condition2) {
    # ...
} else {
    # ...
}


import random
from collections import defaultdict

printdead, printlive = '-#'
maxgenerations = 3
cellcount = 3,3
celltable = defaultdict(int, {
 (1, 2): 1,
 (1, 3): 1,
 (0, 3): 1,
 } ) # Only need to populate with the keys leading to life

##
## Start States
##
# blinker
u = universe = defaultdict(int)
u[(1,0)], u[(1,1)], u[(1,2)] = 1,1,1

## toad
#u = universe = defaultdict(int)
#u[(5,5)], u[(5,6)], u[(5,7)] = 1,1,1
#u[(6,6)], u[(6,7)], u[(6,8)] = 1,1,1

## glider
#u = universe = defaultdict(int)
#maxgenerations = 16
#u[(5,5)], u[(5,6)], u[(5,7)] = 1,1,1
#u[(6,5)] = 1
#u[(7,6)] = 1

## random start
#universe = defaultdict(int,
#                       # array of random start values
#                       ( ((row, col), random.choice((0,1)))
#                         for col in range(cellcount[0])
#                         for row in range(cellcount[1])
#                       ) )  # returns 0 for out of bounds

for i in range(maxgenerations):
    print("\nGeneration %3i:" % ( i, ))
    for row in range(cellcount[1]):
        print("  ", ''.join(str(universe[(row,col)])
                            for col in range(cellcount[0])).replace(
                                '0', printdead).replace('1', printlive))
    nextgeneration = defaultdict(int)
    for row in range(cellcount[1]):
        for col in range(cellcount[0]):
            nextgeneration[(row,col)] = celltable[
                ( universe[(row,col)],
                  -universe[(row,col)] + sum(universe[(r,c)]
                                             for r in range(row-1,row+2)
                                             for c in range(col-1, col+2) )
                ) ]
    universe = nextgeneration


If a = 0
  Debug "a = 0"

ElseIf a > 0
  Debug "a > 0"

Else
  Debug "a < 0"

EndIf


# Generates a new board - either a random one, sample blinker or gliders, or user specified.
gen.board <- function(type="random", nrow=3, ncol=3, seeds=NULL)
{
    if(type=="random")
    {
       return(matrix(runif(nrow*ncol) > 0.5, nrow=nrow, ncol=ncol))
    } else if(type=="blinker")
    {
       seeds <- list(c(2,1),c(2,2),c(2,3))
    } else if(type=="glider")
    {
       seeds <- list(c(1,2),c(2,3),c(3,1), c(3,2), c(3,3))
    }
    board <- matrix(FALSE, nrow=nrow, ncol=ncol)
    for(k in seq_along(seeds))
    {
      board[seeds[[k]][1],seeds[[k]][2]] <- TRUE
    }
    board
}

# Returns the number of living neighbours to a location
count.neighbours <- function(x,i,j)
{
   sum(x[max(1,i-1):min(nrow(x),i+1),max(1,j-1):min(ncol(x),j+1)]) - x[i,j]
}

# Implements the rulebase
determine.new.state <- function(board, i, j)
{
   N <- count.neighbours(board,i,j)
   (N == 3 || (N ==2 && board[i,j]))
}

# Generates the next interation of the board from the existing one
evolve <- function(board)
{
   newboard <- board
   for(i in seq_len(nrow(board)))
   {
      for(j in seq_len(ncol(board)))
      {
         newboard[i,j] <- determine.new.state(board,i,j)
      }
   }
   newboard
}

# Plays the game.  By default, the board is shown in a plot window, though output to the console if possible.
game.of.life <- function(board, nsteps=50, timebetweensteps=0.25, graphicaloutput=TRUE)
{
   if(!require(lattice)) stop("lattice package could not be loaded")
   nr <- nrow(board)

   for(i in seq_len(nsteps))
   {
      if(graphicaloutput)
      {
         print(levelplot(t(board[nr:1,]), colorkey=FALSE))
      } else print(board)

      Sys.sleep(timebetweensteps)

      newboard <- evolve(board)

      if(all(newboard==board))
      {
         message("board is static")
         break
      } else if(sum(newboard) < 1)
      {
         message("everything is dead")
         break
      } else board <- newboard
   }
   invisible(board)
}

# Example usage
game.of.life(gen.board("blinker"))
game.of.life(gen.board("glider", 18, 20))
game.of.life(gen.board(, 50, 50))


if x == 0:
    foo()
elif x == 1:
    bar()
elif x == 2:
    baz()
else:
    boz()


Print "QB64/Qbasic conditional structures"
Dim k As String
Menu 1
View Print 13 To 23
Print "A menu example using the many options of IF statement"
k = " "
12: While k <> ""
    k = UCase$(Input$(1))
    If k = "O" GoTo O
    If k = "F" Then 22
    If k = "S" Then GoSub S: GoTo 12
    If k = "C" Then GoSub 4: GoTo 12
    If k = "E" Then GoSub 5: Exit While
Wend
Cls
Print "the same menu example with Select Case"
Sleep 2
While k <> ""
    k = UCase$(Input$(1))

    Select Case k
        Case "O"
            Print "You choose O"
        Case "F"
            Print "You choose F"
        Case "S"
            Print "You choose S"
        Case "C"
            Print "You choose C"
        Case "E"
            Print "You choose Exit"
            _Delay 1
            Exit While
        Case Else
            Print "Wrong choice"
    End Select
Wend
View Print
Cls
Menu 2
View Print 13 To 23
Print "menu demonstration using ON value GOTO"
k = " "
While k <> ""
    k = Input$(1)
    On Val(k) GOSUB 1, 2, 3, 4, 5
Wend
End

1:
Print "Chosen O"
Return

2:
Print "Chosen F"
Return

3:
Print "Chosen S"
Return

4:
Print "Chosen C"
Return

5:
Print "Chosen E"
If k = "5" Then End
Return

O:
Print "You choose O"
GoTo 12

22:
Print "You choose F"
GoTo 12

S:
Print "You choose S"
Return

Sub Menu (Kind As Integer)
    Locate 7, 33: Color 3, 4
    Print "Choose the item"
    Color 7, 0
    Locate , 33
    If Kind = 1 Then Print "Open a file"; Else Print "1) Open a file";
    Color 14, 1
    Locate , 33
    If Kind = 1 Then Print "O" Else Print "1"
    Color 7, 0

    Locate , 33
    If Kind = 1 Then Print "Find a file"; Else Print "2) Find a file";
    Color 14, 1
    Locate , 33
    If Kind = 1 Then Print "F" Else Print "2"
    Color 7, 0

    Locate , 33
    If Kind = 1 Then Print "Scan a file"; Else Print "3) Scan a file";
    Color 14, 1
    Locate , 33
    If Kind = 1 Then Print "S" Else Print "3"
    Color 7, 0

    Locate , 33
    If Kind = 1 Then Print "Copy a file"; Else Print "4) Copy a file";
    Color 14, 1
    Locate , 33
    If Kind = 1 Then Print "C" Else Print "4"
    Color 7, 0

    Locate , 33
    If Kind = 1 Then Print "Exit from Menu"; Else Print "5) Exit from Menu";
    Color 14, 1
    Locate , 33
    If Kind = 1 Then Print "E" Else Print "5"
    Color 7, 0

End Sub


#lang racket
(require 2htdp/image 2htdp/universe)

;;;
;;; Grid object
;;;

(define (make-empty-grid m n)
  (build-vector m (lambda (y) (make-vector n 0))))

(define rows vector-length)

(define (cols grid)
  (vector-length (vector-ref grid 0)))

(define (make-grid m n living-cells)
  (let loop ([grid (make-empty-grid m n)]
             [cells living-cells])
    (if (empty? cells)
        grid
        (loop (2d-set! grid (caar cells) (cadar cells) 1) (cdr cells)))))

(define (2d-ref grid i j)
  (cond [(< i 0) 0]
        [(< j 0) 0]
        [(>= i (rows grid)) 0]
        [(>= j (cols grid)) 0]
        [else (vector-ref (vector-ref grid i) j)]))

(define (2d-refs grid indices)
  (map (lambda (ind) (2d-ref grid (car ind) (cadr ind))) indices))

(define (2d-set! grid i j val)
  (vector-set! (vector-ref grid i) j val)
  grid)

;;; cartesian product of 2 lists
(define (cart l1 l2)
  (if (empty? l1)
      '()
      (append (let loop ([n (car l1)] [l l2])
                (if (empty? l) '() (cons (list n (car l)) (loop n (cdr l)))))
              (cart (cdr l1) l2))))

;;; Count living cells in the neighbourhood
(define (n-count grid i j)
  (- (apply + (2d-refs grid (cart (list (- i 1) i (+ i 1))
                                  (list (- j 1) j (+ j 1)))))
     (2d-ref grid i j)))

;;;
;;; Rules and updates of the grid
;;;

;;; rules are stored in a 2d array: r_i,j = new state of a cell
;;; in state i with j neighboors
(define conway-rules
  (list->vector (list (list->vector '(0 0 0 1 0 0 0 0 0))
                      (list->vector '(0 0 1 1 0 0 0 0 0)))))

(define (next-state rules grid i j)
  (let ([current (2d-ref grid i j)]
        [N (n-count grid i j)])
    (2d-ref rules current N)))

(define (next-grid rules grid)
  (let ([new-grid (make-empty-grid (rows grid) (cols grid))])
    (let loop ([i 0] [j 0])
      (if (>= i (rows grid))
          new-grid
          (if (>= j (cols grid))
              (loop (+ i 1) 0)
              (begin (2d-set! new-grid i j (next-state rules grid i j))
                     (loop i (+ j 1))))))))

(define (next-grid! rules grid)
  (let ([new-grid (next-grid rules grid)])
    (let loop ((i 0))
      (if (< i (rows grid))
        (begin (vector-set! grid i (vector-ref new-grid i))
               (loop (+ i 1)))
        grid))))

;;;
;;; Image / Animation
;;;

(define (grid->image grid)
  (let ([m (rows grid)] [n (cols grid)] [size 5])
    (let loop ([img (rectangle (* m size) (* n size) "solid" "white")]
               [i 0] [j 0])
      (if (>= i (rows grid))
          img
          (if (>= j (cols grid))
              (loop img (+ i 1) 0)
              (if (= (2d-ref grid i j) 1)
                  (loop (underlay/xy img (* i (+ 1 size)) (* j (+ 1 size))
                                     (square (- size 2) "solid" "black"))
                        i (+ j 1))
                  (loop img i (+ j 1))))))))

(define (game-of-life grid refresh_time)
  (animate (lambda (n)
             (if (= (modulo n refresh_time) 0)
                 (grid->image (next-grid! conway-rules grid))
                 (grid->image grid)))))

;;;
;;; Examples
;;;

(define (blinker)
  (make-grid 3 3 '((0 1) (1 1) (2 1))))

(define (thunder)
  (make-grid 70 50 '((30 19) (30 20) (30 21) (29 17) (30 17) (31 17))))

(define (cross)
  (let loop ([i 0] [l '()])
    (if (>= i 80)
        (make-grid 80 80 l)
        (loop (+ i 1) (cons (list i i) (cons (list (- 79 i) i) l))))))

;;; To run examples:
;;; (game-of-life (blinker) 30)
;;; (game-of-life (thunder) 2)
;;; (game-of-life (cross) 2)


/O> say "23 is greater than 42 is "
... 23 42 > not if [ say "not " ]
... say "true." cr
...
23 is greater than 42 is not true.

Stack empty.

/O> say "23 is less than 42 is "
... 23 42 < not if [ say "not " ]
... say "true." cr
...
23 is less than 42 is true.

Stack empty.

/O> 23 42 = iff
...   [ say "23 is equal to 42." ]
... else
...   [ say "23 is different to 42." ]
... cr
...
23 is different to 42.

Stack empty.

/O> 23 42 != iff
...   [ say "23 is not equal to 42." ]
... else
...   [ say "23 is the same as  42." ]
... cr
...
23 is not equal to 42.

Stack empty.


x <- 0
if(x == 0) print("foo")
x <- 1
if(x == 0) print("foo")
if(x == 0) print("foo") else print("bar")


given lc prompt("Done? ") {
    when 'yes' { return }
    when 'no'  { next }
    default    { say "Please answer either yes or no." }
}


Red [
    Purpose: "Conway's Game of Life"
    Author: "Joe Smith"
]

neigh: [[0 1] [0 -1] [1 0] [-1 0] [1 1] [1 -1] [-1 1] [-1 -1]]
conway: function [petri] [
	new-petri: copy/deep petri
	repeat row length? petri [
		repeat col length? petri [
			live-neigh: 0
			foreach cell neigh [
				try [
					if petri/(:row + cell/1)/(:col + cell/2) = 1 [live-neigh: live-neigh + 1]
				]
			]
			switch petri/:row/:col [
				1	[if any [live-neigh < 2 live-neigh > 3]
						[new-petri/:row/:col: 0]
					]
				0	[if live-neigh = 3 [new-petri/:row/:col: 1]]
	]]]
	clear insert petri new-petri
]

*3-3: [
	[0 1 0]
	[0 1 0]
	[0 1 0]
]

*8-8: [
	[0 0 1 0 0 0 0 0]
	[0 0 0 1 0 0 0 0]
	[0 1 1 1 0 0 0 0]
	[0 0 0 0 0 0 0 0]
	[0 0 0 0 0 0 0 0]
	[0 0 0 0 0 0 0 0]
	[0 0 0 0 0 0 0 0]
	[0 0 0 0 0 0 0 0]
]

display: function [table] [
	foreach row table [
		print replace/all (replace/all to-string row "0" "_") "1" "#"
	] print ""
]

loop 5 [
	display *3-3
	conway *3-3
]
loop 23 [
	display *8-8
	conway *8-8
]


>> if 10 > 2 [print "ten is bigger"]
ten is bigger


condition  [ true statements ] if
condition  [ false statements ] -if
condition  [ true statements  ] [ false statements ] choose


with ada.command_line, ada.containers.indefinite_vectors, ada.text_io;
procedure compare_lengths is
   package string_vector is new ada.containers.indefinite_vectors
     (index_type => Positive, element_type => String);

   function "<" (left, right : String) return Boolean is
   begin
      return left'length > right'length;
   end "<";

   package string_vector_sorting is new string_vector.generic_sorting;
   list : string_vector.Vector;
begin
   for i in 1 .. ada.command_line.argument_count loop
      list.append (ada.command_line.argument (i));
   end loop;
   string_vector_sorting.sort (list);
   for elem of list loop
      ada.text_io.put_line (elem'length'image & ": " & elem);
   end loop;
end compare_lengths;


:w/l [ $. eq? [ #0 ] [ #1 ] choose , ] s:for-each ;

'World d:create
  '.................... w/l
  '.................... w/l
  '.................... w/l
  '..ooo............... w/l
  '....o............... w/l
  '...o................ w/l
  '.................... w/l
  '.................... w/l
  '.................... w/l
  '.................... w/l
  '.................... w/l
  '....ooo............. w/l
  '.................... w/l
  '.................... w/l
  '.................... w/l
  '........ooo......... w/l
  '.......ooo.......... w/l
  '.................... w/l
  '.................... w/l
  '.................... w/l

'Next d:create
  #20 #20 * allot

{{
  'Surrounding var
  :get (rc-v)
    dup-pair [ #0 #19 n:between?
] [email protected] and
    [ &World + [ #20 * ] dip + fetch ] [ drop-pair #0 ] choose ;
  :neighbor?  (rc-) get &Surrounding v:inc-by ;
  :NW (rc-rc) dup-pair [ n:dec ] [email protected]       neighbor? ;
  :NN (rc-rc) dup-pair [ n:dec ] dip       neighbor? ;
  :NE (rc-rc) dup-pair [ n:dec ] dip n:inc neighbor? ;
  :WW (rc-rc) dup-pair   n:dec             neighbor? ;
  :EE (rc-rc) dup-pair   n:inc             neighbor? ;
  :SW (rc-rc) dup-pair [ n:inc ] dip n:dec neighbor? ;
  :SS (rc-rc) dup-pair [ n:inc ] dip       neighbor? ;
  :SE (rc-rc) dup-pair [ n:inc ] [email protected]       neighbor? ;
  :count (rc-rcn)
    #0 !Surrounding NW NN NE
                    WW    EE
                    SW SS SE @Surrounding ;
  :alive (rc-n)
    count #2 #3 n:between? [ #1 ] if; #0 ;
  :dead (rc-n)
    count #3 eq? [ #1 ] if; #0 ;
  :new-state (rc-n)
    dup-pair get #1 eq? &alive &dead choose ;
  :set   (nrc-)  &Next + [ #20 * ] dip + store ;
  :cols (r-)
    #20 [ I over swap new-state rot rot set ] times<with-index> drop ;
  :output (n-) n:-zero? [ $o ] [ $. ] choose c:put sp ;
---reveal---
  :display (-)
    nl &World #20 [ #20 [ fetch-next output ] times nl ] times drop ;
  :gen (-)
    #20 [ I cols ] times<with-index> &Next &World #20 #20 * copy ;
}}

{{
  :divide #20 [ $- c:put ] times sp 'Gen:_ s:put dup n:put nl ;
---reveal---
  :gens (n-)  #0 swap [ display divide  n:inc gen ] times drop ;
}}

#12 gens


if  y  then @=6                        /* Y  must be either   0  or  1  */

if t**2>u  then x=y                    /*simple  IF  with  THEN & ELSE. */
           else x=-y

if t**2>u  then do j=1  for 10;  say prime(j);  end    /*THEN  DO  loop.*/
           else x=-y                                   /*simple  ELSE.  */

if z>w+4  then do                                      /*THEN  DO group.*/
               z=abs(z)
               say 'z='z
               end
          else do;  z=0;  say 'failed.';  end          /*ELSE  DO group.*/

if x>y  &  c*d<sqrt(pz) |,             /*this statement is continued [,]*/
   substr(abc,4,1)=='~'  then  if  z=0  then call punt
                                        else nop       /*NOP pairs up IF*/
                         else  if  z<0  then z=-y      /*alignment helps*/


BEGIN # compare string lengths #
    # returns the length of s using the builtin UPB and LWB operators #
    OP LENGTH = ( STRING s )INT: ( UPB s + 1 ) - LWB s;
    # prints s and its length #
    PROC print string = ( STRING s )VOID:
         print( ( """", s, """ has length: ", whole( LENGTH s, 0 ), " bytes.", newline ) );
    STRING shorter     = "short";
    STRING not shorter = "longer";
    IF LENGTH shorter >  LENGTH not shorter THEN print string( shorter ) FI;
    print string( not shorter );
    IF LENGTH shorter <= LENGTH not shorter THEN print string( shorter ) FI
END


      sv ← 'defg' 'hijklm' 'abc' 'abcd'
      ⍉(⍴¨sv[⍒sv]),[0.5]sv[⍒sv]
 6  hijklm
 4  defg
 4  abcd
 3  abc


sortByLength: function [strs][
    map sort.descending.by:'v
        map strs 'str -> #[s: str, v: size str]
        'z -> z\s
]

A: "I am string"
B: "I am string too"

sA: size A
sB: size B

if? sA < sB ->
    print ["string ->" A "(" sA ") is smaller than string ->" B "(" sB ")"]
else [
    if? sA > sB ->
        print ["string ->" A "(" sA ") is larger than string ->" B "(" sB ")"]
    else ->
        print ["string ->" A "(" sA ") and string ->" B "(" sB ") are of equal length"]
]

print ["sorted strings (by length):" sortByLength ["abcd" "123456789" "abcdef" "1234567"]]


/*REXX program runs and displays the Conway's game of life, it stops after  N  repeats. */
signal on halt                                   /*handle a  cell growth  interruptus.  */
parse arg peeps  '(' rows  cols  empty  life!  clearScreen  repeats  generations .
       rows =        p(rows               3)     /*the maximum number of cell  rows.    */
       cols =        p(cols               3)     /* "     "       "    "   "  columns.  */
        emp = pickChar(empty        'blank')     /*an empty cell character  (glyph).    */
   clearScr =        p(clearScreen        0)     /* "1"   indicates to clear the screen.*/
      life! = pickChar(life!            '☼')     /*the gylph kinda looks like an amoeba.*/
       reps =        p(repeats            2)     /*stop pgm  if there are  two  repeats.*/
generations =        p(generations      100)     /*the number of  generations  allowed. */
sw= max(linesize() - 1,  cols)                   /*usable screen width for the display. */
#reps= 0;        $.= emp                         /*the universe is new,  ··· and barren.*/
gens=abs(generations)                            /*used for a  programming  convenience.*/
x= space(peeps); upper x                         /*elide superfluous spaces; uppercase. */
if x==''         then x= "BLINKER"               /*if nothing specified,  use  BLINKER. */
if x=='BLINKER'  then x= "2,1 2,2 2,3"
if x=='OCTAGON'  then x= "1,5 1,6 2,4 2,7 3,3 3,8 4,2 4,9 5,2 5,9 6,3 6,8 7,4 7,7 8,5 8,6"
call assign.                                     /*assign the initial state of all cells*/
call showCells                                   /*show the  initial state of the cells.*/
     do life=1  for gens;      call [email protected]      /*construct  next  generation of cells.*/
     if generations>0 | life==gens  then call showCells    /*should cells be displayed? */
     end   /*life*/                              /* [↑]  cell colony grows, lives, dies.*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
showCells: if clearScr  then 'CLS'               /*  ◄───  change 'command' for your OS.*/
           call showRows                         /*show the rows in the proper order.   */
           say right(copies('▒', sw)  life, sw)  /*show a fence between the generations.*/
           if _==''  then exit                   /*if there's no life, then stop the run*/
           if !._    then #reps= #reps + 1       /*we detected a repeated cell pattern. */
           !._= 1                                /*existence  state and compare  later. */
           if reps\==0 & #reps<=reps then return /*so far, so good,   regarding repeats.*/
           say
           say center('"Life" repeated itself' reps "times, simulation has ended.",sw,'▒')
           exit                                  /*stick a fork in it,  we're all done. */
/*───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/
$:         parse arg _row,_col;                    return $._row._col==life!
assign$:   do r=1  for rows;   do c=1  for cols;   $.r.c= @.r.c;                                    end;    end;       return
assign.:   do while x\==''; parse var x r "," c x; $.r.c=life!; rows=max(rows,r); cols=max(cols,c); end; life=0; !.=0; return
assign?:   ?=$.r.c; n=neighbors(); if ?==emp then do;if n==3 then ?=life!; end; else if n<2 | n>3 then ?=emp; @.r.c=?; return
[email protected]:   @.=emp;      do r=1  for rows;  do c=1  for cols;  call assign?;  end;  end;            call assign$;       return
halt:      say;         say "REXX program  (Conway's Life)  halted.";    say;      exit 0
neighbors: return $(r-1,c-1)  +  $(r-1,c)  +  $(r-1,c+1)  +  $(r,c-1)  +  $(r,c+1)  +  $(r+1,c-1)  +  $(r+1,c)  +  $(r+1,c+1)
p:         return word(arg(1), 1)
pickChar:  _=p(arg(1)); arg u .; if u=='BLANK' then _=" "; L=length(_); if L==3 then _=d2c(_); if L==2 then _=x2c(_);  return _
showRows:  _=; do r=rows by -1 for rows; z=; do c=1 for cols; z=z||$.r.c; end; z=strip(z,'T',emp); say z; _=_||z; end; return


If[cond]
|:
    Do Something[]
:||:
    Do Something Else[]
:|


If x == 1
   SomeFunc1()
But x == 2
   SomeFunc2()
Else
   SomeFunc()
Ok


string A, B, t = '\t';

void comp(string A, string B) {
    if (length(A) >= length(B)) {
        write(A+t, length(A));
        write(B+t, length(B));
    } else {
        write(B+t, length(B));
        write(A+t, length(A));
    }
}

comp("abcd", "123456789");


list := ["abcd","123456789","abcdef","1234567"]

sorted := []
for i, s in list
    sorted[0-StrLen(s), s] := s
for l, obj in sorted
{
    i := A_Index
    for s, v in obj
    {
        if (i = 1)
            result .= """" s """ has length " 0-l " and is the longest string.`n"
        else if (i < sorted.Count())
            result .= """"s """ has length " 0-l " and is neither the longest nor the shortest string.`n"
        else
            result .= """"s """ has length " 0-l " and is the shorted string.`n"
    }
}
MsgBox % result


# syntax: GAWK -f COMPARE_LENGTH_OF_TWO_STRINGS.AWK
BEGIN {
    main("abcd","123456789")
    main("longer","short")
    main("hello","world")
    exit(0)
}
function main(Sa,Sb,  La,Lb) {
    La = length(Sa)
    Lb = length(Sb)
    if (La > Lb) {
      printf("a>b\n%3d %s\n%3d %s\n\n",La,Sa,Lb,Sb)
    }
    else if (La < Lb) {
      printf("a<b\n%3d %s\n%3d %s\n\n",Lb,Sb,La,Sa)
    }
    else {
      printf("a=b\n%3d %s\n%3d %s\n\n",Lb,Sb,La,Sa)
    }
}


def game_of_life(name, size, generations, initial_life=nil)
  board = new_board size
  seed board, size, initial_life
  print_board board, name, 0
  reason = generations.times do |gen|
    new = evolve board, size
    print_board new, name, gen+1
    break :all_dead if barren? new, size
    break :static   if board == new
    board = new
  end
  if    reason == :all_dead then puts "no more life."
  elsif reason == :static   then puts "no movement"
  else                           puts "specified lifetime ended"
  end
  puts
end

def new_board(n)
  Array.new(n) {Array.new(n, 0)}
end

def seed(board, n, points=nil)
  if points.nil?
    # randomly seed board
    indices = []
    n.times {|x| n.times {|y| indices << [x,y] }}
    indices.shuffle[0,10].each {|x,y| board[y][x] = 1}
  else
    points.each {|x, y| board[y][x] = 1}
  end
end

def evolve(board, n)
  new = new_board n
  n.times {|i| n.times {|j| new[i][j] = fate board, i, j, n}}
  new
end

def fate(board, i, j, n)
  i1 = [0, i-1].max; i2 = [i+1, n-1].min
  j1 = [0, j-1].max; j2 = [j+1, n-1].min
  sum = 0
  for ii in (i1..i2)
    for jj in (j1..j2)
      sum += board[ii][jj] if not (ii == i and jj == j)
    end
  end
  (sum == 3 or (sum == 2 and board[i][j] == 1)) ? 1 : 0
end

def barren?(board, n)
  n.times {|i| n.times {|j| return false if board[i][j] == 1}}
  true
end

def print_board(m, name, generation)
  puts "#{name}: generation #{generation}"
  m.each {|row| row.each {|val| print "#{val == 1 ? '#' : '.'} "}; puts}
end

game_of_life "blinker", 3, 2, [[1,0],[1,1],[1,2]]
game_of_life "glider", 4, 4, [[1,0],[2,1],[0,2],[1,2],[2,2]]
game_of_life "random", 5, 10


' Boolean Evaluations
'
' > Greater Than
' < Less Than
' >= Greater Than Or Equal To
' <= Less Than Or Equal To
' = Equal to

x = 0

if x = 0 then print "Zero"

' --------------------------
' if/then/else
if x = 0 then
print "Zero"
else
print "Nonzero"
end if

' --------------------------
' not
if x then
print "x has a value."
end if
if not(x) then
print "x has no value."
end if

' --------------------------
' if .. end if
if x = 0 then
print "Zero"
goto [surprise]
end if
wait

if x = 0 then goto [surprise]
print "No surprise."
wait

[surprise]
print "Surprise!"
wait

' --------------------------
' case numeric
num = 3

select case num
case 1
print "one"

case 2
print "two"

case 3
print "three"

case else
print "other number"

end select

' --------------------------
' case character
var$="blue"

select case var$

case "red"
print "red"

case "green"
print "green"

case else
print "color unknown"

end select


Compare ← >·(⍒⊑¨)⊸⊏≠⊸⋈¨

•Show Compare ⟨"hello", "person"⟩
•Show Compare ⟨"abcd", "123456789", "abcdef", "1234567"⟩


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

int cmp(const int* a, const int* b)
{
    return *b - *a; // reverse sort!
}

void compareAndReportStringsLength(const char* strings[], const int n)
{
    if (n > 0)
    {
        char* has_length = "has length";
        char* predicate_max = "and is the longest string";
        char* predicate_min = "and is the shortest string";
        char* predicate_ave = "and is neither the longest nor the shortest string";

        int* si = malloc(2 * n * sizeof(int));
        if (si != NULL)
        {
            for (int i = 0; i < n; i++)
            {
                si[2 * i] = strlen(strings[i]);
                si[2 * i + 1] = i;
            }
            qsort(si, n, 2 * sizeof(int), cmp);

            int max = si[0];
            int min = si[2 * (n - 1)];

            for (int i = 0; i < n; i++)
            {
                int length = si[2 * i];
                char* string = strings[si[2 * i + 1]];
                char* predicate;
                if (length == max)
                    predicate = predicate_max;
                else if (length == min)
                    predicate = predicate_min;
                else
                    predicate = predicate_ave;
                printf("\"%s\" %s %d %s\n",
                    string, has_length, length, predicate);
            }

            free(si);
        }
        else
        {
            fputs("unable allocate memory buffer", stderr);
        }
    }
}

int main(int argc, char* argv[])
{
    char* list[] = { "abcd", "123456789", "abcdef", "1234567" };

    compareAndReportStringsLength(list, 4);

    return EXIT_SUCCESS;
}


use std::collections::HashMap;
use std::collections::HashSet;

type Cell = (i32, i32);
type Colony = HashSet<Cell>;

fn print_colony(col: &Colony, width: i32, height: i32) {
    for y in 0..height {
        for x in 0..width {
            print!("{} ",
                if col.contains(&(x, y)) {"O"}
                else {"."}
            );
        }
        println!();
    }
}

fn neighbours(&(x,y): &Cell) -> Vec<Cell> {
    vec![
        (x-1,y-1), (x,y-1), (x+1,y-1),
        (x-1,y),            (x+1,y),
        (x-1,y+1), (x,y+1), (x+1,y+1),
    ]
}

fn neighbour_counts(col: &Colony) -> HashMap<Cell, i32> {
    let mut ncnts = HashMap::new();
    for cell in col.iter().flat_map(neighbours) {
        *ncnts.entry(cell).or_insert(0) += 1;
    }
    ncnts
}

fn generation(col: Colony) -> Colony {
    neighbour_counts(&col)
        .into_iter()
        .filter_map(|(cell, cnt)|
            match (cnt, col.contains(&cell)) {
                (2, true) |
                (3, ..) => Some(cell),
                _ => None
        })
        .collect()
}

fn life(init: Vec<Cell>, iters: i32, width: i32, height: i32) {
    let mut col: Colony = init.into_iter().collect();
    for i in 0..iters+1
    {
        println!("({})", &i);
        if i != 0 {
            col = generation(col);
        }
        print_colony(&col, width, height);
    }
}

fn main() {
    let blinker = vec![
        (1,0),
        (1,1),
        (1,2)];

    life(blinker, 3, 3, 3);

    let glider = vec![
                (1,0),
                        (2,1),
        (0,2),  (1,2),  (2,2)];

    life(glider, 20, 8, 8);
}


// This function will only be compiled if we are compiling on Linux
#[cfg(target_os = "linux")]
fn running_linux() {
    println!("This is linux");
}
#[cfg(not(target_os = "linux"))]
fn running_linux() {
    println!("This is not linux");
}

// If we are on linux, we must be using glibc
#[cfg_attr(target_os = "linux", target_env = "gnu")]
// We must either be compiling for ARM or on a little endian machine that doesn't have 32-bit pointers pointers, on a
// UNIX like OS and only if we are doing a test build
#[cfg(all(
        any(target_arch = "arm", target_endian = "little"),
        not(target_pointer_width = "32"),
        unix,
        test
        ))]
fn highly_specific_function() {}


#include <iostream>
#include <algorithm>
#include <string>
#include <list>

using namespace std;

bool cmp(const string& a, const string& b)
{
    return b.length() < a.length(); // reverse sort!
}

void compareAndReportStringsLength(list<string> listOfStrings)
{
    if (!listOfStrings.empty())
    {
        char Q = '"';
        string has_length(" has length ");
        string predicate_max(" and is the longest string");
        string predicate_min(" and is the shortest string");
        string predicate_ave(" and is neither the longest nor the shortest string");

        list<string> ls(listOfStrings); // clone to avoid side-effects
        ls.sort(cmp);
        int max = ls.front().length();
        int min = ls.back().length();

        for (list<string>::iterator s = ls.begin(); s != ls.end(); s++)
        {
            int length = s->length();
            string* predicate;
            if (length == max)
                predicate = &predicate_max;
            else if (length == min)
                predicate = &predicate_min;
            else
                predicate = &predicate_ave;

            cout << Q << *s << Q << has_length << length << *predicate << endl;
        }
    }
}

int main(int argc, char* argv[])
{
    list<string> listOfStrings{ "abcd", "123456789", "abcdef", "1234567" };
    compareAndReportStringsLength(listOfStrings);

    return EXIT_SUCCESS;
}


using System;
using System.Collections.Generic;

namespace example
{
    class Program
    {
        static void Main(string[] args)
        {
            var strings = new string[] { "abcd", "123456789", "abcdef", "1234567" };
            compareAndReportStringsLength(strings);
        }

        private static void compareAndReportStringsLength(string[] strings)
        {
            if (strings.Length > 0)
            {
                char Q = '"';
                string hasLength = " has length ";
                string predicateMax = " and is the longest string";
                string predicateMin = " and is the shortest string";
                string predicateAve = " and is neither the longest nor the shortest string";
                string predicate;

                (int, int)[] li = new (int, int)[strings.Length];
                for (int i = 0; i < strings.Length; i++)
                    li[i] = (strings[i].Length, i);
                Array.Sort(li, ((int, int) a, (int, int) b) => b.Item1 - a.Item1);
                int maxLength = li[0].Item1;
                int minLength = li[strings.Length - 1].Item1;

                for (int i = 0; i < strings.Length; i++)
                {
                    int length = li[i].Item1;
                    string str = strings[li[i].Item2];
                    if (length == maxLength)
                        predicate = predicateMax;
                    else if (length == minLength)
                        predicate = predicateMin;
                    else
                        predicate = predicateAve;
                    Console.WriteLine(Q + str + Q + hasLength + length + predicate);
                }
            }
        }

    }
}


;;An R6RS Scheme implementation of Conway's Game of Life --- assumes
;;all cells outside the defined grid are dead

;if n is outside bounds of list, return 0 else value at n
(define (nth n lst)
  (cond ((> n (length lst)) 0)
        ((< n 1) 0)
        ((= n 1) (car lst))
        (else (nth (- n 1) (cdr lst)))))

;return the next state of the supplied universe
(define (next-universe universe)
  ;value at (x, y)
  (define (cell x y)
    (if (list? (nth y universe))
        (nth x (nth y universe))
        0))
  ;sum of the values of the cells surrounding (x, y)
  (define (neighbor-sum x y)
    (+ (cell (- x 1) (- y 1))
       (cell (- x 1) y)
       (cell (- x 1) (+ y 1))
       (cell x (- y 1))
       (cell x (+ y 1))
       (cell (+ x 1) (- y 1))
       (cell (+ x 1) y)
       (cell (+ x 1) (+ y 1))))
  ;next state of the cell at (x, y)
  (define (next-cell x y)
    (let ((cur (cell x y))
          (ns (neighbor-sum x y)))
      (cond ((and (= cur 1)
                  (or (< ns 2) (> ns 3)))
             0)
            ((and (= cur 0) (= ns 3))
             1)
            (else cur))))
  ;next state of row n
  (define (row n out)
    (let ((w (length (car universe))))
      (if (= (length out) w)
          out
          (row n
               (cons (next-cell (- w (length out)) n)
                     out)))))
  ;a range of ints from bot to top
  (define (int-range bot top)
    (if (> bot top) '()
        (cons bot (int-range (+ bot 1) top))))
  (map (lambda (n)
         (row n '()))
       (int-range 1 (length universe))))

;represent the universe as a string
(define (universe->string universe)
  (define (prettify row)
    (apply string-append
           (map (lambda (b)
                  (if (= b 1) "#" "-"))
                row)))
  (if (null? universe)
      ""
      (string-append (prettify (car universe))
                     "\n"
                     (universe->string (cdr universe)))))

;starting with seed, show reps states of the universe
(define (conway seed reps)
  (when (> reps 0)
    (display (universe->string seed))
    (newline)
    (conway (next-universe seed) (- reps 1))))

;; --- Example Universes --- ;;

;blinker in a 3x3 universe
(conway '((0 1 0)
          (0 1 0)
          (0 1 0)) 5)

;glider in an 8x8 universe
(conway '((0 0 1 0 0 0 0 0)
          (0 0 0 1 0 0 0 0)
          (0 1 1 1 0 0 0 0)
          (0 0 0 0 0 0 0 0)
          (0 0 0 0 0 0 0 0)
          (0 0 0 0 0 0 0 0)
          (0 0 0 0 0 0 0 0)
          (0 0 0 0 0 0 0 0)) 30)


    if EXPR then
      -- CODE
    elsif EXPR then
      -- CODE
    else
      -- CODE
    end;


  if (n == 12) "twelve" else "not twelve"

  today match {
    case Monday =>
      Compute_Starting_Balance;
    case Friday =>
      Compute_Ending_Balance;
    case Tuesday =>
      Accumulate_Sales
    case _ => {}
  }


bundle agent __main__
{
  vars:
      "strings" slist => { "abcd", "123456789", "abcdef", "1234567" };

      "sorted[$(with)]"
        string => "$(strings)",
        with => string_length( "$(strings)" );

      "sort_idx" slist => reverse( sort( getindices( "sorted" ), lex ) );

  reports:
      "'$(sorted[$(sort_idx)])' is $(sort_idx) characters in length.";
}


*** (1) TWO STRINGS ***
LONGER STRING (13)
SHORT STRING (12)

*** (2) MORE THAN 2 STRINGS***
SHE DOESN'T STUDY GERMAN ON MONDAY (34)
EVERY CHILD LIKES AN ICE CREAM (30)
THE COURSE STARTS NEXT SUNDAY (29)
DOES SHE LIVE IN PARIS? (23)
SHE SWIMS EVERY MORNING (23)
THE EARTH IS SPHERICAL (22)
WE SEE THEM EVERY WEEK (22)
HE DOESN'T TEACH MATH (21)
CATS HATE WATER (15)
I LIKE TEA (10)


program demo_sort_indexed
implicit none

   call print_sorted_by_length( [character(len=20) :: "shorter","longer"] )
   call print_sorted_by_length( [character(len=20) :: "abcd","123456789","abcdef","1234567"] )
   call print_sorted_by_length( [character(len=20) :: 'the','quick','brown','fox','jumps','over','the','lazy','dog'])

contains

subroutine print_sorted_by_length(list)
character(len=*) :: list(:)
integer :: i

   list(sort_int(len_trim(list)))=list ! sort by length from small to large
   write(*,'(i9,1x,a)')(len_trim(list(i)), list(i),i=size(list),1,-1)! print from last to first
   write(*,*)

end subroutine print_sorted_by_length

function sort_int(input) result(counts) ! **very** inefficient mini index sort
integer :: input(:), counts(size(input)), i
   counts=[(count(input(i) > input)+count(input(i) == input(:i)),i=1, size(input) )]
end function sort_int

end program demo_sort_indexed


if condition1 then instructions1
[elseif condition2 then instructions2]
....
[else instructionse]
end


local fn MyArraySortFunction( obj1 as CFTypeRef, obj2 as CFTypeRef, context as ptr ) as NSComparisonResult
  NSComparisonResult result = NSOrderedDescending
  if len(obj1) >= len(obj2) then result = NSOrderedAscending
end fn = result

void local fn DoIt
  CFStringRef string1 = @"abcd", string2 = @"abcdef", s

  if len(string1) >= len(string2)
    print string1,len(string1)
    print string2,len(string2)
  else
    print string2,len(string2)
    print string1,len(string1)
  end if

  print
  text ,,,,, 85

  CFArrayRef strings = @[@"abcd",@"123456789",@"abcdef",@"1234567"]
  strings = fn ArraySortedArrayUsingFunction( strings, @fn MyArraySortFunction, NULL )
  for s in strings
    print s,len(s)
  next
end fn

window 1

fn DoIt

HandleEvents


PROCEDURE Main()
	LOCAL s1 := "The long string"
	LOCAL s2 := "The short string"
	LOCAL a  := { s1, s2 }
	LOCAL s3

	? s3 := "Here is how you can print the longer string first using Harbour language"
	?
	? "-------------------------------------------"
	PrintTheLongerFirst( a )

	a := hb_ATokens( s3, " " )
	? "-------------------------------------------"
	PrintTheLongerFirst( a )
	? "-------------------------------------------"
	RETURN

FUNCTION PrintTheLongerFirst( a )
	LOCAL n, tmp
	a := ASort( a,,, {|x,y| Len(x) > Len(y) } )
	n:= Len( a[1] )
	AEval( a, { |e| tmp := n-Len(e), Qout( e,  Space(tmp) + ;
	            hb_strFormat( "(length = %d chars)", Len(e) ) ) } )
	RETURN NIL


task s1 s2 = do
  let strs = if length s1 > length s2 then [s1, s2] else [s2, s1]
  mapM_ (\s -> putStrLn $ show (length s) ++ "\t" ++ show s) strs


Init_state=[0 0 0;...
            1 1 1;...
            0 0 0];
console_output=%T;

if (atomsIsLoaded('IPCV') | atomsIsLoaded('SIVP')) & ~console_output then
    Input=imread('initial_state.bmp');  //Comment this three lines in case
    Init_state=~im2bw(Input,0.1);       //there is no input image but
    Init_state=1.0.*Init_state;         //you still want the graphic window
    scf(0); clf();
    imshow(~Init_state);
    set(gca(),"isoview","on");
end

Curr_state=1.0.*Init_state;
Grid_size=size(Init_state);
Gens=4;

function varargout=neighbourhood(A,i,j)
    R_top=i-1;
    if i==1 then
        R_top=1;
    end

    R_bottom=i+1;
    if i==Grid_size(1) then
        R_bottom=Grid_size(1);
    end

    R_left=j-1;
    if j==1 then
        R_left=1;
    end

    C_right=j+1;
    if j==Grid_size(2) then
        C_right=Grid_size(2);
    end

    varargout=list(A(R_top:R_bottom,R_left:C_right));
endfunction

function []=console_print(Grid)
    String_grid=string(Grid);
    for i=1:size(Grid,'r')
        for j=1:size(Grid,'c')
            if Grid(i,j) then
                String_grid(i,j)="#";
            else
                String_grid(i,j)=" ";
            end
        end
    end
    disp(String_grid);
endfunction

neighbours=[];
Next_state=[];

for gen=1:Gens
    Next_state=zeros(Init_state);

    for i=1:Grid_size(1)
        for j=1:Grid_size(2)
            neighbours=zeros(3,3);
            neighbours=neighbourhood(Curr_state,i,j);

            Sum_neighbours=sum(neighbours)-1*Curr_state(i,j);

            Alive=Curr_state(i,j);
            if Alive then
                if Sum_neighbours<2 then
                    Next_state(i,j)=0;
                elseif Sum_neighbours==2 | Sum_neighbours==3 then
                    Next_state(i,j)=1;
                elseif Sum_neighbours>3 then
                    Next_state(i,j)=0;
                end
            else
                if Sum_neighbours==3 then
                    Next_state(i,j)=1;
                end
            end
        end
    end

    if (atomsIsLoaded('IPCV') | atomsIsLoaded('SIVP')) & ~console_output then
        imshow(~Next_state);
        sleep(50);
    else
        sleep(50);
        disp("Generation "+string(gen)+":")
        console_print(Next_state);
    end

    if sum(Next_state)==0 | Curr_state==Next_state then
        disp('ALL CELLS HAVE DIED OR BECAME INERT');
        disp('No. of Generations: '+string(gen))
        break
    end

    Curr_state=Next_state;
end


if condition then
  statement
end if;

if condition then
  statement1
else
  statement2;
end if;

if condition1 then
  statement1
elsif condition2 then
  statement2;
end if;

if condition1 then
  statement1
elsif condition2 then
  statement2;
else
  statement3;
end if;


if x == 1
  foo()
else if x == 2
  bar()
else
  foobar()
end if


   NB. solution
   NB. `Haruno-umi Hinemosu-Notari Notarikana'
   NB. Spring ocean ; Swaying gently ; All day long.

   ,/ _2 }.\ ": (;~ #)&>  <@(7&u:);._2 '春の海 ひねもすのたり のたりかな '
│3│春の海        │
│7│ひねもすのたり│
│5│のたりかな    │

   NB.  # y  is the tally of items (penultimate dimension) in the array y
   # 323 43 5j3
3

   # 'literal (a string)'
18

   /: 'cbad'   NB. index ordering vector (grade up)
2 1 0 3

   ;: 'j tokenize a sentence.'
┌─┬────────┬─┬─────────┐
│j│tokenize│a│sentence.│
└─┴────────┴─┴─────────┘

   #S:0 ;: 'j tokenize a sentence.'  NB. length of leaves (lowest box level)
1 8 1 9

   A=: '1234567 abcd 123456789 abcdef'  NB. global assignment

   (\: #S:0) ;: A  NB. order by grade down
┌─────────┬───────┬──────┬────┐
│123456789│1234567│abcdef│abcd│
└─────────┴───────┴──────┴────┘

   (;:'length literal') , ((;~ #)&> \: #S:0) ;: A  NB. box incompatible types with header
┌──────┬─────────┐
│length│literal  │
├──────┼─────────┤
│9     │123456789│
├──────┼─────────┤
│7     │1234567  │
├──────┼─────────┤
│6     │abcdef   │
├──────┼─────────┤
│4     │abcd     │
└──────┴─────────┘

   (;:'len vector') , ((;~ #)&> \: #S:0) 0 1 2 3 ; 0 1 ; (i. 8) ; 0
┌───┬───────────────┐
│len│vector         │
├───┼───────────────┤
│8  │0 1 2 3 4 5 6 7│
├───┼───────────────┤
│4  │0 1 2 3        │
├───┼───────────────┤
│2  │0 1            │
├───┼───────────────┤
│1  │0              │
└───┴───────────────┘


package stringlensort;

import java.io.PrintStream;
import java.util.Arrays;
import java.util.Comparator;

public class ReportStringLengths {

    public static void main(String[] args) {
        String[] list = {"abcd", "123456789", "abcdef", "1234567"};
        String[] strings = args.length > 0 ? args : list;

        compareAndReportStringsLength(strings);
    }

    /**
     * Compare and report strings length to System.out.
     *
     * @param strings an array of strings
     */
    public static void compareAndReportStringsLength(String[] strings) {
        compareAndReportStringsLength(strings, System.out);
    }

    /**
     * Compare and report strings length.
     *
     * @param strings an array of strings
     * @param stream the output stream to write results
     */
    public static void compareAndReportStringsLength(String[] strings, PrintStream stream) {
        if (strings.length > 0) {
            strings = strings.clone();
            final String QUOTE = "\"";
            Arrays.sort(strings, Comparator.comparing(String::length));
            int min = strings[0].length();
            int max = strings[strings.length - 1].length();
            for (int i = strings.length - 1; i >= 0; i--) {
                int length = strings[i].length();
                String predicate;
                if (length == max) {
                    predicate = "is the longest string";
                } else if (length == min) {
                    predicate = "is the shortest string";
                } else {
                    predicate = "is neither the longest nor the shortest string";
                }
                //@todo: StringBuilder may be faster
                stream.println(QUOTE + strings[i] + QUOTE + " has length " + length
                        + " and " + predicate);
            }
        }
    }
}


set starting_condition to ((0, 0), (1, 0), (2, 0), (-1, -1), (0, -1), (1, -1))

RunGameOfLife starting_condition

to printColony colonies
    set xCoords to the first item of each item of colonies
    set yCoords to the second item of each item of colonies
    set min_x to the min of xCoords
    set max_x to the max of xCoords
    set min_y to the min of yCoords
    set max_y to the max of yCoords
    repeat for y in min_y..max_y
        set row to ()
        repeat for x in min_x..max_x
            if (x, y) is in colonies
                push "#" into row
            else
                push "-" into row
            end if
        end repeat
        join row using ""
        put row
    end repeat
end printColony

to neighboursOf coordinate
    return ( \
            coordinate + (-1, 1), \
            coordinate + (0, 1), \
            coordinate + (1, 1), \
            coordinate + (-1, 0), \
            coordinate + (1, 0), \
            coordinate + (-1, -1), \
            coordinate + (0, -1), \
            coordinate + (1, -1), \
            )
end neighboursOf

to WillNextGenHaveCell colony, coordinate
    set neighbour_count to the number of items in (each item of neighboursOf(coordinate) where each is in colony)
    if coordinate is in colony
        return neighbour_count is in (2, 3)
    else
        return neighbour_count equals 3
    end if
end WillNextGenHaveCell

to RunGameOfLife colony
    printColony colony
    set the listInsertionMode to "nested"
    repeat 10 times
        set new_colony to ()

        set xCoords to the first item of each item of colony
        set yCoords to the second item of each item of colony

        set min_x to (the min of xCoords) - 1
        set max_x to (the max of xCoords) + 1
        set min_y to (the min of yCoords) - 1
        set max_y to (the max of yCoords) + 1

        repeat for y in min_y..max_y
            repeat for x in min_x..max_x
                if WillNextGenHaveCell(colony, (x, y))
                    insert (x, y) into new_colony
                end if
            end repeat
        end repeat
        set colony to new_colony
        printColony colony
        wait 1 second
    end repeat
end RunGameOfLife


 statement::=  if conditional_expression then statement else statement
   if X=Y then K:=I else K:=J
 statement::=  if conditional_expression then statement
   if X=Y then K:=I


"Conditionals in Slate are really messages sent to Boolean objects. Like Smalltalk. (But the compiler might optimize some cases)"
 balance > 0
     ifTrue: [inform: 'still sitting pretty!'.]
     ifFalse: [inform: 'No money till payday!'.].


/**
 * Compare and report strings lengths.
 *
 * @param {Element} input - a TextArea DOM element with input
 * @param {Element} output - a TextArea DOM element for output
 */
function compareStringsLength(input, output) {

  // Safe defaults.
  //
  output.value = "";
  let output_lines = [];

  // Split input into an array of lines.
  //
  let strings = input.value.split(/\r\n|\r|\n/g);

  // Is strings array empty?
  //
  if (strings && strings.length > 0) {

    // Remove leading and trailing spaces.
    //
    for (let i = 0; i < strings.length; i++)
      strings[i] = strings[i].trim();

    // Sort by lengths.
    //
    strings.sort((a, b) => a.length - b.length);

    // Remove empty strings.
    //
    while (strings[0] == "")
      strings.shift();

    // Check if any strings remain.
    //
    if (strings && strings.length > 0) {

      // Get min and max length of strings.
      //
      const min = strings[0].length;
      const max = strings[strings.length - 1].length;

      // Build output verses - longest strings first.
      //
      for (let i = strings.length - 1; i >= 0; i--) {
        let length = strings[i].length;
        let predicate;
        if (length == max) {
          predicate = "is the longest string";
        } else if (length == min) {
          predicate = "is the shortest string";
        } else {
          predicate = "is neither the longest nor the shortest string";
        }
        output_lines.push(`"${strings[i]}" has length ${length} and ${predicate}\n`);
      }

      // Send all lines from output_lines array to an TextArea control.
      //
      output.value = output_lines.join('');
    }
  }
}

document.getElementById("input").value = "abcd\n123456789\nabcdef\n1234567";
compareStringsLength(input, output);


life(Cells(2))[I, J] :=
	let
		numNeighbors := Cells[I-1,J-1] + Cells[I-1,J] + Cells[I-1,J+1] +
				Cells[I,J-1]   +/*current cell*/Cells[I,J+1] +
				Cells[I+1,J-1] + Cells[I+1,J] + Cells[I+1,J+1];
	in
		0 when I=1 or J=1 or I=size(Cells) or J=size(Cells[I]) //On Border
	else
		0 when numNeighbors < 2 or numNeighbors > 3 //Cell Dies
	else
		1 when Cells[I,J] = 1 and numNeighbors = 2 or numNeighbors = 3 //Cell lives on or is born.
	else
		Cells[I,J]; //No Change

stressTestInput(n(0))[y,x] :=
		0 when not y = n / 2
	else
		1
	foreach y within 1 ... n,
		x within 1 ... n;


 balance > 0
     ifTrue: [Transcript cr; show: 'still sitting pretty!'.]
     ifFalse: [Transcript cr; show: 'No money till payday!'.].

 balance < 10 ifTrue:[ self goGetSomeMoney ].

 balance > 1000 ifTrue:[ self beHappy ].

 (balance < 10)
    ifFalse:[ self gotoHappyHour ]
    ifTrue:[ self noDrinksToday ].


	A = "true"
* "if-then-else"
if	A "true"			:s(goTrue)f(goFalse)
goTrue	output = "A is TRUE"		:(fi)
goFalse	output = "A is not TRUE"	:(fi)
fi

* "switch"
switch		A ("true" | "false") . switch	:s($("case" switch))f(default)
casetrue	output = "A is TRUE"	:(esac)
casefalse	output = "A is FALSE"	:(esac)
default		output = "A is neither FALSE nor TRUE"
esac
end


s = "niño"
println("Position  Char Bytes\n==============================")
for (i, c) in enumerate(s)
    println("$i          $c     $(sizeof(c))")
end


def s1: "longer";
def s2: "shorter😀";

[s1,s2]
| sort_by(length)
| reverse[]
| "\"\(.)\" has length (codepoints) \(length) and utf8 byte length \(utf8bytelength)."


{def L.new
 {lambda {:s}
  {if {S.empty? {S.rest :s}}
   then {P.new {S.first :s} nil}
   else {P.new {S.first :s} {L.new {S.rest :s}}}}}}
-> L.new

{def L.disp
 {lambda {:l}
  {if {W.equal? :l nil}
   then
   else {br} {W.length {P.left :l}} : {P.left :l}
        {L.disp {P.right :l}}}}}
-> L.disp


program life;

const
  initialMatrix =
    [".....",
     "..#..",
     "...#.",
     ".###.",
     "....."];

loop
init
  s := initialLiveSet();
do
  output(s);
  nm := {[[x+dx, y+dy], [x, y]]: [x, y] in s, dx in {-1..1}, dy in {-1..1}};
  s := {c: t = nm{c} | 3 in {#t, #(t less c)}};
end;

proc output(s);
  system("clear");
  (for y in [0..24])
    (for x in [0..78])
      nprint(if [x, y] in s then "#" else " " end);
    end;
    print();
  end;
  select([], 250);
end proc;

proc initialLiveSet();
  return {[x,y]: row = initialMatrix(y), c = row(x) | c = '#'};
end proc;

end program;


var odd = 13;
if odd % 2 != 0 {
    print("odd");
}


function test(list)
  table.sort(list, function(a,b) return #a > #b end)
  for _,s in ipairs(list) do print(#s, s) end
end
test{"abcd", "123456789", "abcdef", "1234567"}


list = {"abcd", "123456789", "abcdef", "1234567"};
[email protected][list, StringLength] // TableForm


import strformat, unicode

const
  S1 = "marche"
  S2 = "marché"

echo &"“{S2}”, byte length = {S2.len}, code points: {S2.toRunes.len}"
echo &"“{S1}”, byte length = {S1.len}, code points: {S1.toRunes.len}"


program compareLengthOfStrings(output);

const
	specimenA = 'RosettaCode';
	specimenB = 'Pascal';
	specimenC = 'Foobar';
	specimenD = 'Pascalish';

type
	specimen = (A, B, C, D);
	specimens = set of specimen value [];

const
	specimenMinimum = A;
	specimenMaximum = D;

var
	{ the explicit range min..max serves as a safeguard to update max const }
	list: array[specimenMinimum..specimenMaximum] of string(24)
		value [A: specimenA; B: specimenB; C: specimenC; D: specimenD];
	lengthRelationship: array[specimen] of specimens;

procedure analyzeLengths;
var
	left, right: specimen;
begin
	for left := specimenMinimum to specimenMaximum do
	begin
		for right := specimenMinimum to specimenMaximum do
		begin
			if length(list[left]) < length(list[right]) then
			begin
				lengthRelationship[right] := lengthRelationship[right] + [right]
			end
		end
	end
end;

procedure printSortedByLengths;
var
	i: ord(specimenMinimum)..ord(specimenMaximum);
	s: specimen;
begin
	{ first the string longer than all other strings }
	{ lastly print the string not longer than any other string }
	for i := ord(specimenMaximum) downto ord(specimenMinimum) do
	begin
		{ for demonstration purposes: iterate over a set }
		for s in [specimenMinimum..specimenMaximum] do
		begin
			{ card returns the cardinality ("population count") }
			if card(lengthRelationship[s]) = i then
			begin
				writeLn(length(list[s]):8, ' ', list[s])
			end
		end
	end
end;

begin
	analyzeLengths;
	printSortedByLengths
end.


(tc +)

(datatype subtype
  (subtype B A); X : B;
  _____________________
  X : A;)

(datatype integer
  if (integer? X)
  ___________
  X: integer;

  ________________________
  (subtype integer number);)

(datatype bit
  if (< X 2)
  _______
  X: bit;

  _____________________
  (subtype bit integer);)

(datatype row

  _________
  [] : row;

  C : bit; Row : row;
  ===================
  [C | Row] : row;)

(datatype universe

  ______________
  [] : universe;

  R : row; Uni : universe;
  ========================
  [R | Uni] : universe;)

(define conway-nth
  \\ returns value of x from row if it exists, else 0
  { number --> row --> bit }
  _ [] -> 0
  N _ -> 0 where (< N 0)
  0 [A|B] -> A
  N [A|B] -> (conway-nth (- N 1) B))

(define row-retrieve
  { number --> universe --> row }
  _ [] -> []
  0 [] -> []
  0 [A|B] -> A
  N [A|B] -> (row-retrieve (- N 1) B))

(define cell-retrieve
  { number --> number --> universe --> bit }
  X Y Universe -> (conway-nth X (row-retrieve Y Universe)))

(define neighbors
  \\ takes an X and Y, retrieves the number of neighbors
  { number --> number --> universe --> number }
  X Y Universe -> (let ++ (+ 1)
                       -- (/. X (- X 1))
                    (+ (cell-retrieve (++ X) Y Universe)
                       (cell-retrieve (++ X) (++ Y) Universe)
                       (cell-retrieve (++ X) (-- Y) Universe)
                       (cell-retrieve (-- X) Y Universe)
                       (cell-retrieve (-- X) (++ Y) Universe)
                       (cell-retrieve (-- X) (-- Y) Universe)
                       (cell-retrieve X (++ Y) Universe)
                       (cell-retrieve X (-- Y) Universe))))

(define handle-alive
  { number --> number --> universe --> bit }
  X Y Universe -> (if (or (= (neighbors X Y Universe) 2)
                          (= (neighbors X Y Universe) 3))
                      1 0))

(define handle-dead
  { number --> number --> universe --> bit }
  X Y Universe -> (if (= (neighbors X Y Universe) 3)
                      1 0))

(define next-row
  \\ first argument must be a previous row, second must be 0 when
  \\ first called, third must be a Y value and the final must be the
  \\ current universe
  { row --> number --> number --> universe --> row }
  [] _ _ _ -> []
  [1|B] X Y Universe -> (cons (handle-alive X Y Universe)
                              (next-row B (+ X 1) Y Universe))
  [_|B] X Y Universe -> (cons (handle-dead X Y Universe)
                              (next-row B (+ X 1) Y Universe)))

(define next-universe
  \\ both the first and second arguments must be the same universe,
  \\ the third must be 0 upon first call
  { universe --> number --> universe --> universe }
  [] _ _ -> []
  [Row|Rest] Y Universe -> (cons (next-row Row 0 Y Universe)
                                 (next-universe Rest (+ Y 1) Universe)))

(define display-row
  { row --> number }
  [] -> (nl)
  [1|Rest] -> (do (output "* ")
                  (display-row Rest))
  [_|Rest] -> (do (output "  ")
                  (display-row Rest)))

(define display-universe
  { universe --> number }
  [] -> (nl 2)
  [Row|Rest] -> (do (display-row Row)
                    (display-universe Rest)))

(define iterate-universe
  { number --> universe --> number }
  0 _ -> (nl)
  N Universe -> (do (display-universe Universe)
                    (iterate-universe (- N 1)
                                      (next-universe Universe 0 Universe))))

(iterate-universe
 10
 [[0 0 0 0 0 0]
  [0 0 0 0 0 0]
  [0 0 1 1 1 0]
  [0 1 1 1 0 0]
  [0 0 0 0 0 0]
  [0 0 0 0 0 0]])


CASE WHEN a THEN b ELSE c END

DECLARE @n INT
SET @n=124
print CASE WHEN @n=123 THEN 'equal' ELSE 'not equal' END

--If/ElseIf expression
SET @n=5
print CASE WHEN @n=3 THEN 'Three' WHEN @n=4 THEN 'Four' ELSE 'Other' END


#!/usr/bin/perl

use strict; # https://rosettacode.org/wiki/Compare_length_of_two_strings
use warnings;

for ( 'shorter thelonger', 'abcd 123456789 abcdef 1234567' )
  {
  print "\nfor strings => $_\n";
  printf "length %d: %s\n", length(), $_
    for sort { length $b <=> length $a } split;
  }


with javascript_semantics
sequence list = {"abcd","123456789","abcdef","1234567"},
         lens = apply(list,length),
         tags = reverse(custom_sort(lens,tagset(length(lens))))
papply(true,printf,{1,{"%s (length %d)\n"},columnize({extract(list,tags),extract(lens,tags)})})


<?php

function retrieveStrings()
{
    if (isset($_POST['input'])) {
        $strings = explode("\n", $_POST['input']);
    } else {
        $strings = ['abcd', '123456789', 'abcdef', '1234567'];
    }
    return $strings;
}

function setInput()
{
    echo join("\n", retrieveStrings());
}

function setOutput()
{
    $strings = retrieveStrings();

    // Remove empty strings
    //
    $strings = array_map('trim', $strings);
    $strings = array_filter($strings);

    if (!empty($strings)) {
        usort($strings, function ($a, $b) {
            return strlen($b) - strlen($a);
        });
        $max_len = strlen($strings[0]);
        $min_len = strlen($strings[count($strings) - 1]);
        foreach ($strings as $s) {
            $length = strlen($s);
            if ($length == $max_len) {
                $predicate = "is the longest string";
            } elseif ($length == $min_len) {
                $predicate = "is the shortest string";
            } else {
                $predicate = "is neither the longest nor the shortest string";
            }
            echo "$s has length $length and $predicate\n";
        }
    }
}

?>

<!DOCTYPE html>

        <form action=<?php echo $_SERVER['SCRIPT_NAME'] ?> method="post" accept-charset="utf-8">

                Input:

                <textarea rows='20' cols='80' name='input'><?php setInput(); ?></textarea>

            <input type="submit" value="press to compare strings">
            </input>

                Output:

                <textarea rows='20' cols='80' name='output'><?php setOutput(); ?></textarea>

        </form>


var w = Num(`tput cols`)
var h = Num(`tput lines`)
var r = "\033[H"

var dirs = [[-1,-1], [-1, 0], [-1, 1], [ 0,-1],
            [ 0, 1], [ 1,-1], [ 1, 0], [ 1, 1]]

var universe = h.of { w.of {1.rand < 0.1} }

func iterate {
    var new = h.of { w.of(false) }
    static rx = (^h ~X ^w)
    for i,j in rx {
        var neighbor = 0
        for y,x in (dirs.map {|dir| dir »+« [i, j] }) {
            universe[y % h][x % w] && ++neighbor
            neighbor > 3 && break
        }
        new[i][j] = (universe[i][j]
                        ? (neighbor==2 || neighbor==3)
                        : (neighbor==3))
    }
    universe = new
}

STDOUT.autoflush(true)

loop {
    print r
    say universe.map{|row| row.map{|cell| cell ? '#' : ' '}.join }.join("\n")
    iterate()
}


clear
set obs 4
gen a = cond(mod(_n, 2)==1, "A", "B")
list, noobs noheader

  +---+
  | A |
  | B |
  | A |
  | B |
  +---+


kama (kweli) {
  andika("statement")
} au (kweli /* condition */) {
  andika("statement")
} au (kweli /* condition */) {
  andika("statement")
} sivyo {
  andika("statement")
}


A = 'I am string'
B = 'I am string too'

if len(A) > len(B):
    print('"' + A + '"', 'has length', len(A), 'and is the longest of the two strings')
    print('"' + B + '"', 'has length', len(B), 'and is the shortest of the two strings')
elif len(A) < len(B):
    print('"' + B + '"', 'has length', len(B), 'and is the longest of the two strings')
    print('"' + A + '"', 'has length', len(A), 'and is the shortest of the two strings')
else:
    print('"' + A + '"', 'has length', len(A), 'and it is as long as the second string')
    print('"' + B + '"', 'has length', len(B), 'and it is as long as the second string')


Dim Words(1 To 4) As String
Dim Lengths As Integer, Index As Integer, Position As Integer, Done As String, Index2 As Integer
' inititialization
Words(1) = "abcd"
Words(2) = "123456789"
Words(3) = "abcdef"
Words(4) = "1234567"

Print " Word         Length"
For Index2 = 1 To 4 Step 1
    Lengths = 0
    Position = 0
    For Index = 1 To 4 Step 1
        If Lengths < Len(Words(Index)) And InStr(Done, Words(Index) + " ") = 0 Then
            Lengths = Len(Words(Index))
            Position = Index
        End If
    Next Index
    Done = Done + Words(Position) + " /@/"
    Print Words(Position), Len(Words(Position))
Next Index2


  $ "A short string of"
  $ "A slightly longer string of"

  2dup size dip size > if swap
  dup echo$ sp size echo say " characters." cr
  dup echo$ sp size echo say " characters." cr cr

  '  [ $ "From troubles of the world I turn to ducks,"
       $ "Beautiful comical things"
       $ "Sleeping or curled"
       $ "Their heads beneath white wings"
       $ "By water cool,"
       $ "Or finding curious things"
       $ "To eat in various mucks"
       $ "Beneath the pool," ]
   []  swap witheach [ do nested join ]

  sortwith [ size dip size < ]
  witheach [ echo$ cr ]


say 'Strings (👨👩👧👦, 🤔🇺🇸, BOGUS!) sorted: "longest" first:';
say "$_: characters:{.chars},  Unicode code points:{.codes},  UTF-8 bytes:{.encode('UTF8').bytes},  UTF-16 bytes:{.encode('UTF16').bytes}" for <👨👩👧👦 BOGUS! 🤔🇺🇸>.sort: -*.chars;


COMMENT A PORT OF AN R6RS SCHEME IMPLEMENTATION OF CONWAY'S GAME OF LIFE TO SIMULA --- ASSUMES ;
COMMENT ALL CELLS OUTSIDE THE DEFINED GRID ARE DEAD ;

BEGIN

COMMENT FIRST WE NEED CONS, CAR, CDR, LENGTH AND MAP TO SIMULATE SCHEME ;

CLASS ATOM;;

ATOM CLASS CELL(ALIVE); INTEGER ALIVE;;

ATOM CLASS LIST(A1, A2); REF(ATOM) A1, A2;;

REF(LIST) PROCEDURE CONS(A1, A2); REF(ATOM) A1, A2;
    CONS :- NEW LIST(A1, A2);

REF(ATOM) PROCEDURE CAR(LST); REF(LIST) LST;
    CAR :- LST.A1;

REF(ATOM) PROCEDURE CDR(LST); REF(LIST) LST;
    CDR :- LST.A2;

INTEGER PROCEDURE LENGTH(LST); REF(LIST) LST;
    LENGTH := IF LST == NONE THEN 0 ELSE 1 + LENGTH(CDR(LST));

REF(LIST) PROCEDURE MAP(F, LST); PROCEDURE F IS REF(ATOM) PROCEDURE F(ARG); REF(ATOM) ARG;; REF(LIST) LST;
    MAP :- IF LST == NONE THEN NONE ELSE CONS(F(CAR(LST)), MAP(F, CDR(LST)));

COMMENT NOW FOLLOWS THE PROBLEM SPECIFIC PART ;

COMMENT IF N IS OUTSIDE BOUNDS OF LIST, RETURN 0 ELSE VALUE AT N ;
REF(ATOM) PROCEDURE NTH(N, LST); INTEGER N; REF(LIST) LST;
    NTH :- IF N > LENGTH(LST) THEN NEW CELL(0) ELSE
           IF N < 1 THEN NEW CELL(0) ELSE
           IF N = 1 THEN CAR(LST) ELSE NTH(N - 1, CDR(LST));

COMMENT RETURN THE NEXT STATE OF THE SUPPLIED UNIVERSE ;
REF(LIST) PROCEDURE NEXTUNIVERSE(UNIVERSE); REF(LIST) UNIVERSE;
BEGIN

    COMMENT VALUE AT (X, Y) ;
    INTEGER PROCEDURE VALUEAT(X, Y); INTEGER X, Y;
    BEGIN
        REF(ATOM) A;
        A :- NTH(Y, UNIVERSE);
        INSPECT A
            WHEN LIST DO
                VALUEAT := NTH(X, THIS LIST) QUA CELL.ALIVE
            OTHERWISE
                VALUEAT := 0;
    END VALUEAT;

    COMMENT SUM OF THE VALUES OF THE CELLS SURROUNDING (X, Y) ;
    INTEGER PROCEDURE NEIGHBORSUM(X, Y); INTEGER X, Y;
        NEIGHBORSUM :=
            VALUEAT(X - 1, Y - 1)
          + VALUEAT(X - 1, Y    )
          + VALUEAT(X - 1, Y + 1)
          + VALUEAT(X,     Y - 1)
          + VALUEAT(X,     Y + 1)
          + VALUEAT(X + 1, Y - 1)
          + VALUEAT(X + 1, Y    )
          + VALUEAT(X + 1, Y + 1);

    COMMENT NEXT STATE OF THE CELL AT (X, Y) ;
    INTEGER PROCEDURE NEXTCELL(X, Y); INTEGER X, Y;
    BEGIN
        INTEGER CUR, NS;
        CUR := VALUEAT(X, Y);
        NS := NEIGHBORSUM(X, Y);
        NEXTCELL := IF CUR = 1 AND (NS < 2 OR NS > 3) THEN 0 ELSE
                    IF CUR = 0 AND NS = 3 THEN 1 ELSE CUR;
    END NEXTCELL;

    COMMENT NEXT STATE OF ROW N ;
    REF(LIST) PROCEDURE ROW(N, OUT); INTEGER N; REF(LIST) OUT;
    BEGIN
        INTEGER W, O;
        W := LENGTH(CAR(UNIVERSE));
        O := LENGTH(OUT);
        ROW :- IF W = O THEN OUT ELSE ROW(N, CONS(NEW CELL(NEXTCELL(W - O, N)), OUT));
    END ROW;

    COMMENT A RANGE OF INTS FROM BOT TO TOP ;
    REF(LIST) PROCEDURE INTRANGE(BOT, TOP); INTEGER BOT, TOP;
        INTRANGE :- IF BOT > TOP THEN NONE ELSE CONS(NEW CELL(BOT), INTRANGE(BOT + 1, TOP));

    REF(ATOM) PROCEDURE LAMBDA(N); REF(ATOM) N;
        LAMBDA :- ROW(N QUA CELL.ALIVE, NONE);

    NEXTUNIVERSE :- MAP(LAMBDA, INTRANGE(1, LENGTH(UNIVERSE)));

END NEXTUNIVERSE;

COMMENT DISPLAY THE UNIVERSE ;
PROCEDURE DISPLAY(LST); REF(LIST) LST;
BEGIN
    WHILE LST =/= NONE DO
    BEGIN
        REF(LIST) LI;
        LI :- CAR(LST);
        WHILE LI =/= NONE DO
        BEGIN
            REF(CELL) CE;
            CE :- CAR(LI);
            OUTCHAR(IF CE.ALIVE = 1 THEN '#' ELSE '-');
            LI :- CDR(LI);
        END;
        OUTIMAGE;
        LST :- CDR(LST);
    END;
END DISPLAY;

COMMENT STARTING WITH SEED, SHOW REPS STATES OF THE UNIVERSE ;
PROCEDURE CONWAY(SEED, REPS); REF(LIST) SEED; INTEGER REPS;
BEGIN
    IF REPS > 0 THEN
    BEGIN
        DISPLAY(SEED);
        OUTIMAGE;
        CONWAY(NEXTUNIVERSE(SEED), REPS - 1);
    END;
END CONWAY;

REF(CELL) O, L;
O :- NEW CELL(0);
L :- NEW CELL(1);

COMMENT BLINKER IN A 3X3 UNIVERSE ;
! (CONWAY '((0 1 0)
            (0 1 0)
            (0 1 0)) 5) ;
CONWAY(CONS(CONS(O, CONS(L, CONS(O, NONE))),
       CONS(CONS(O, CONS(L, CONS(O, NONE))),
       CONS(CONS(O, CONS(L, CONS(O, NONE))),
       NONE))), 5);

COMMENT GLIDER IN AN 8X8 UNIVERSE ;
!(CONWAY '((0 0 1 0 0 0 0 0)
           (0 0 0 1 0 0 0 0)
           (0 1 1 1 0 0 0 0)
           (0 0 0 0 0 0 0 0)
           (0 0 0 0 0 0 0 0)
           (0 0 0 0 0 0 0 0)
           (0 0 0 0 0 0 0 0)
           (0 0 0 0 0 0 0 0)) 30) ;
OUTIMAGE;

CONWAY(CONS(CONS(O, CONS(O, CONS(L, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, NONE)))))))),
       CONS(CONS(O, CONS(O, CONS(O, CONS(L, CONS(O, CONS(O, CONS(O, CONS(O, NONE)))))))),
       CONS(CONS(O, CONS(L, CONS(L, CONS(L, CONS(O, CONS(O, CONS(O, CONS(O, NONE)))))))),
       CONS(CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, NONE)))))))),
       CONS(CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, NONE)))))))),
       CONS(CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, NONE)))))))),
       CONS(CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, NONE)))))))),
       CONS(CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, NONE)))))))),
       NONE)))))))), 30);

END.


templates foo
  when <=0> do 'zero' -> !OUT::write
  when <..0> do
    'negative ' -> !OUT::write
    -$ -> #
  when <?($ mod 2 <=0>)> do 'even' -> !OUT::write
  otherwise 'odd' -> !OUT::write
end foo


if {$foo == 3} {
    puts "foo is three"
} elseif {$foo == 4} {
    puts "foo is four"
} else {
    puts "foo is neither three nor four"
}


/* REXX */
list = '"abcd","123456789","abcdef","1234567"'
Do i=1 By 1 While list>''
  Parse Var list s.i ',' list
  s.i=strip(s.i,,'"')
  End
n=i-1
Do While n>1
  max=0
  Do i=1 To n
    If length(s.i)>max Then Do
      k=i
      max=length(s.i)
      End
    End
  Call o s.k
  If k<n Then
    s.k=s.n
  n=n-1
  End
Call o s.1
Exit
o:
Say length(arg(1)) arg(1)
Return


see "working..." + nl

list = ["abcd","123456789"]
if len(list[1]) > len(list[2])
   first = list[1]
   second = list[2]
else
   first = list[2]
   second = list[1]
ok

see "Compare length of two strings:" + nl
see "" + first + " len = " + len(first) + nl + second + " len = " + len(second) + nl
see "done..." + nl


a, b = "Given two strings", "of different length"
[a,b].sort_by{|s| - s.size }.each{|s| puts s + " (size: #{s.size})"}

list = ["abcd","123456789","abcdef","1234567"]
puts list.sort_by{|s|- s.size}


fn compare_and_report<T: ToString>(string1: T, string2: T) -> String {
    let strings = [string1.to_string(), string2.to_string()];
    let difference = strings[0].len() as i32 - strings[1].len() as i32;
    if difference == 0 { // equal
        format!("\"{}\" and \"{}\" are of equal length, {}", strings[0], strings[1], strings[0].len())
    } else if difference > 1 { // string1 > string2
        format!("\"{}\" has length {} and is the longest\n\"{}\" has length {} and is the shortest", strings[0], strings[0].len(), strings[1], strings[1].len())
    } else { // string2 > string1
        format!("\"{}\" has length {} and is the longest\n\"{}\" has length {} and is the shortest", strings[1], strings[1].len(), strings[0], strings[0].len())
    }
}

fn main() {
    println!("{}", compare_and_report("a", "b"));
    println!("\n{}", compare_and_report("cd", "e"));
    println!("\n{}", compare_and_report("f", "gh"));
}


"Blinker"
GameOfLife withAliveCells: { 4@2. 4@3. 4@4. 3@3. 4@3. 5@3 } ofSize: 10@10.

"Toad"
GameOfLife withAliveCells: { 2@4. 3@4. 4@4. 3@3. 4@3. 5@3 } ofSize: 10@10


// Compare lenth of two strings, in V
// Tectonics: v run compare-length-of-two-strings.v
module main

// starts here
pub fn main() {
    mut strs := ["abcd","123456789"]
    println("Given: $strs")
    strs.sort_by_len()
    for i := strs.len-1; i >= 0; i-- {
        println("${strs[i]}: with length ${strs[i].len}")
    }

    // more than 2 strings. note = vs :=, := for definition, = for assignment
    strs = ["abcd","123456789","abcdef","1234567"]
    println("\nGiven: $strs")
    strs.sort_by_len()
    for i := strs.len-1; i >= 0; i-- {
        println("${strs[i]}: with length ${strs[i].len}")
    }
}


import "./upc" for Graphemes

var printCounts = Fn.new { |s1, s2, c1, c2|
   var l1 = (c1 > c2) ? [s1, c1] : [s2, c2]
   var l2 = (c1 > c2) ? [s2, c2] : [s1, c1]
   System.print(  "%(l1[0]) : length %(l1[1])")
   System.print(  "%(l2[0]) : length %(l2[1])\n")
}

var codepointCounts = Fn.new { |s1, s2|
   var c1 = s1.count
   var c2 = s2.count
   System.print("Comparison by codepoints:")
   printCounts.call(s1, s2, c1, c2)
}

var byteCounts = Fn.new { |s1, s2|
   var c1 = s1.bytes.count
   var c2 = s2.bytes.count
   System.print("Comparison by bytes:")
   printCounts.call(s1, s2, c1, c2)
}

var graphemeCounts = Fn.new { |s1, s2|
   var c1 = Graphemes.clusterCount(s1)
   var c2 = Graphemes.clusterCount(s2)
   System.print("Comparison by grapheme clusters:")
   printCounts.call(s1, s2, c1, c2)
}

for (pair in [ ["nino", "niño"], ["👨👩👧👦", "🤔🇺🇸"] ]) {
    codepointCounts.call(pair[0], pair[1])
    byteCounts.call(pair[0], pair[1])
    graphemeCounts.call(pair[0], pair[1])
}

var list = ["abcd", "123456789", "abcdef", "1234567"]
System.write("Sorting in descending order by length in codepoints:\n%(list) -> ")
list.sort { |a, b| a.count > b.count }
System.print(list)


-- save these lines in a file called
-- setupworld.sql

-- turn off feedback for cleaner display

SET feedback off

-- 3 x 3 world

-- alive has coordinates of living cells

DROP TABLE alive;

CREATE TABLE alive (x NUMBER,y NUMBER);

-- three alive up the middle
--  *
--  *
--  *

INSERT INTO alive VALUES (2,1);
INSERT INTO alive VALUES (2,2);
INSERT INTO alive VALUES (2,3);

commit;

-- save these lines in a file called
newgeneration.SQL

-- adjact contains one row for each pair of
-- coordinates that is adjacent to a living cell

DROP TABLE adjacent;

CREATE TABLE adjacent (x NUMBER,y NUMBER);

-- add row for each of the 8 adjacent squares

INSERT INTO adjacent SELECT x-1,y-1 FROM alive;
INSERT INTO adjacent SELECT x-1,y FROM alive;
INSERT INTO adjacent SELECT x-1,y+1 FROM alive;
INSERT INTO adjacent SELECT x,y-1 FROM alive;
INSERT INTO adjacent SELECT x,y+1 FROM alive;
INSERT INTO adjacent SELECT x+1,y-1 FROM alive;
INSERT INTO adjacent SELECT x+1,y FROM alive;
INSERT INTO adjacent SELECT x+1,y+1 FROM alive;

commit;

-- delete rows for squares that are outside the world

DELETE FROM adjacent WHERE x<1 OR y<1 OR x>3 OR y>3;

commit;

-- table counts is the number of live cells
-- adjacent to that point

DROP TABLE counts;

CREATE TABLE counts AS
SELECT x,y,COUNT(*) n
FROM adjacent a
GROUP BY x,y;

--    C   N                 new C
--    1   0,1             ->  0  # Lonely
--    1   4,5,6,7,8       ->  0  # Overcrowded
--    1   2,3             ->  1  # Lives
--    0   3               ->  1  # It takes three to give birth!
--    0   0,1,2,4,5,6,7,8 ->  0  # Barren

-- delete the ones who die

DELETE FROM alive a
WHERE
((a.x,a.y) NOT IN (SELECT x,y FROM counts)) OR
((SELECT c.n FROM counts c WHERE a.x=c.x AND a.y=c.y) IN
(1,4,5,6,7,8));

-- insert the ones that are born

INSERT INTO alive a
SELECT x,y FROM counts c
WHERE c.n=3 AND
((c.x,c.y) NOT IN (SELECT x,y FROM alive));

commit;

-- create output table

DROP TABLE output;

CREATE TABLE output AS
SELECT rownum y,' ' x1,' ' x2,' ' x3
FROM dba_tables WHERE rownum < 4;

UPDATE output SET x1='*'
WHERE (1,y) IN
(SELECT x,y FROM alive);

UPDATE output SET x2='*'
WHERE (2,y) IN
(SELECT x,y FROM alive);

UPDATE output SET x3='*'
WHERE (3,y) IN
(SELECT x,y FROM alive);

commit

-- output configuration

SELECT x1||x2||x3 WLD
FROM output
ORDER BY y DESC;


// numbers and objects
if(%num == 1)
{
	foo();
}
else if(%obj == MyObject.getID())
{
	bar();
}
else
{
	deusEx();
}

// strings
if(%str $= "Hello World")
{
	foo();
}
else if(%str $= "Bye World")
{
	bar();
}
else
{
	deusEx();
}


string 0;               \use zero-terminated string convention

func    StrLen(A);      \Return number of characters in an ASCIIZ string
char    A;
int     I;
for I:= 0 to -1>>1 do
        if A(I) = 0 then return I;

char    List;
int     M, N, SN, Len, Max;
[List:= ["abcd","123456789","abcdef","1234567"];
for M:= 0 to 3 do
    [Max:= 0;
    for N:= 0 to 3 do
        [Len:= StrLen(@List(N,0));
        if Len > Max then [Max:= Len;  SN:= N];
        ];
    Text(0, @List(SN,0));
    Text(0, " length is ");  IntOut(0, StrLen(@List(SN,0)));  CrLf(0);
    List(SN, 0):= 0;    \truncate largest string
    ];
]


Terminator equ 0      ;null terminator
PrintChar equ &BB5A   ;Amstrad CPC BIOS call, prints accumulator to screen as an ASCII character.

        org &8000

	ld hl,String1
	ld de,String2
	call CompareStringLengths

	jp nc, Print_HL_First
		ex de,hl
Print_HL_First:
	push bc
		push hl
			call PrintString
		pop hl
		push hl
			ld a,' '
			call PrintChar
			call getStringLength
			ld a,b
			call ShowHex_NoLeadingZeroes
			call NewLine
		pop hl
	pop bc

	ex de,hl
	push bc
		push hl
			call PrintString
		pop hl
		push hl
			ld a,' '
			call PrintChar
			call getStringLength
			ld a,b
			call ShowHex_NoLeadingZeroes
			call NewLine
		pop hl
	pop bc
ReturnToBasic:
	RET

String1:
	byte "Hello",Terminator
String2:
	byte "Goodbye",Terminator

;;;;;; RELEVANT SUBROUTINES - PRINTSTRING AND NEWLINE CREATED BY KEITH S. OF CHIBIAKUMAS
CompareStringLengths:
	;HL = string 1
	;DE = string 2
	;CLOBBERS A,B,C
	push hl
	push de
	ex de,hl
	call GetStringLength
	ld b,c

	ex de,hl
	call GetStringLength
	ld a,b
	cp c
	pop de
	pop hl
	ret
	;returns carry set if HL < DE, zero set if equal, zero & carry clear if HL >= DE
	;returns len(DE) in C, and len(HL) in B.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
GetStringLength:
		ld b,0
loop_getStringLength:
		ld a,(hl)
		cp Terminator
		ret z
		inc hl
		inc b
		jr loop_getStringLength
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
NewLine:
	push af
	ld a,13		;Carriage return
	call PrintChar
	ld a,10		;Line Feed
	call PrintChar
	pop af
	ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
PrintString:
	ld a,(hl)
	cp Terminator
	ret z
	inc hl
	call PrintChar
	jr PrintString
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ShowHex_NoLeadingZeroes:
;useful for printing values where leading zeroes don't make sense,
; 	such as money etc.
	push af
		and %11110000
		ifdef gbz80      ;game boy
			swap a
		else             ;zilog z80
			rrca
			rrca
			rrca
			rrca
		endif
		or a
		call nz,PrintHexChar
		;if top nibble of A is zero, don't print it.
	pop af
	and %00001111
	or a
	ret z	;if bottom nibble of A is zero, don't print it!
	jp PrintHexChar
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
PrintHexChar:
	or a	  ;Clear Carry Flag
	daa
	add a,&F0
	adc a,&40 ;This sequence converts a 4-bit hex digit to its ASCII equivalent.
	jp PrintChar


struct Cell: Hashable {
  var x: Int
  var y: Int
}

struct Colony {
  private var height: Int
  private var width: Int
  private var cells: Set<Cell>

  init(cells: Set<Cell>, height: Int, width: Int) {
    self.cells = cells
    self.height = height
    self.width = width
  }

  private func neighborCounts() -> [Cell: Int] {
    var counts = [Cell: Int]()

    for cell in cells.flatMap(Colony.neighbors(for:)) {
      counts[cell, default: 0] += 1
    }

    return counts
  }

  private static func neighbors(for cell: Cell) -> [Cell] {
    return [
      Cell(x: cell.x - 1, y: cell.y - 1),
      Cell(x: cell.x,     y: cell.y - 1),
      Cell(x: cell.x + 1, y: cell.y - 1),
      Cell(x: cell.x - 1, y: cell.y),
      Cell(x: cell.x + 1, y: cell.y),
      Cell(x: cell.x - 1, y: cell.y + 1),
      Cell(x: cell.x,     y: cell.y + 1),
      Cell(x: cell.x + 1, y: cell.y + 1),
    ]
  }

  func printColony() {
    for y in 0..<height {
      for x in 0..<width {
        let char = cells.contains(Cell(x: x, y: y)) ? "0" : "."

        print("\(char) ", terminator: "")
      }

      print()
    }
  }

  mutating func run(iterations: Int) {
    print("(0)")
    printColony()
    print()

    for i in 1...iterations {
      print("(\(i))")
      runGeneration()
      printColony()
      print()
    }
  }

  private mutating func runGeneration() {
    cells = Set(neighborCounts().compactMap({keyValue in
      switch (keyValue.value, cells.contains(keyValue.key)) {
      case (2, true), (3, _):
        return keyValue.key
      case _:
        return nil
      }
    }))
  }
}

let blinker = [Cell(x: 1, y: 0), Cell(x: 1, y: 1), Cell(x: 1, y: 2)] as Set

var col = Colony(cells: blinker, height: 3, width: 3)

print("Blinker: ")
col.run(iterations: 3)

let glider = [
  Cell(x: 1, y: 0),
  Cell(x: 2, y: 1),
  Cell(x: 0, y: 2),
  Cell(x: 1, y: 2),
  Cell(x: 2, y: 2)
] as Set

col = Colony(cells: glider, height: 8, width: 8)

print("Glider: ")
col.run(iterations: 20)


! IF-ELSEIF-ELSE-END IF
! SELECT-CASE
! ON GOTO, ON GOSUB

IF expr_booleana THEN
   sentencia(s)
END IF

IF expr_booleana1 THEN
   sentencia(s)
ELSEIF expr_booleana2 THEN
   sentencia(s)
ELSEIF expr_booleana3 THEN
   sentencia(s)
ELSE
   sentencia(s)
END IF

SELECT CASE expr_booleana
CASE 1
     sentencia(s)
CASE 2
     sentencia(s)
CASE ELSE
     sentencia(s)
END SELECT

ON expresión GOTO label1, label2 ELSE label3

ON expresión Gosub label1, label2 ELSE label3


module gol;

  parameter NUM_ROWS = 20;
  parameter NUM_COLS = 32;

  bit [NUM_COLS:1] cell[1:NUM_ROWS];
  bit clk;

  initial begin
    cell[10][10:8] = 3'b111;
    cell[11][10:8] = 3'b100;
    cell[12][10:8] = 3'b010;
    repeat(8) #5 clk = ~clk;
  end

  always @(posedge clk) begin
    foreach (cell[y,x]) begin
      automatic int count = $countones({ cell[y-1][x-1+:3], cell[y][x-1], cell[y][x+1], cell[y+1][x-1+:3] });
      if (count == 3) cell[y][x] <= 1'b1;
      else if (count != 2) cell[y][x] <= 1'b0;
    end
  end

  always @(negedge clk) begin
    $display("--");
    foreach (cell[y]) $display( "  %b", cell[y] );
  end

endmodule


$$ MODE TUSCRIPT

condition="c"
IF (condition=="a") THEN
   ---> do something
ELSEIF (condition=="b") THEN
   ---> do something
ELSE
   ---> do something
ENDIF


@(choose :shortest x)
@x:@y
@(or)
@x<[email protected]
@(or)
@[email protected]
@(end)


package require Tcl 8.5

proc main {} {
    evolve 3 blinker [initialize_tableau {3 3} {{0 1} {1 1} {2 1}}]
    evolve 5 glider  [initialize_tableau {4 4} {{0 1} {1 2} {2 0} {2 1} {2 2}}]
}

proc evolve {generations name tableau} {
    for {set gen 1} {$gen <= $generations} {incr gen} {
        puts "$name generation $gen:"
        print $tableau
        set tableau [next_generation $tableau]
    }
    puts ""
}

proc initialize_tableau {size initial_life} {
    lassign $size ::max_x ::max_y
    set tableau [blank_tableau]
    foreach point $initial_life {
        lset tableau {*}$point 1
    }
    return $tableau
}

proc blank_tableau {} {
    return [lrepeat $::max_x [lrepeat $::max_y 0]]
}

proc print {tableau} {
    foreach row $tableau {puts [string map {0 . 1 #} [join $row]]}
}

proc next_generation {tableau} {
    set new [blank_tableau]
    for {set x 0} {$x < $::max_x} {incr x} {
        for {set y 0} {$y < $::max_y} {incr y} {
            lset new $x $y [fate [list $x $y] $tableau]
        }
    }
    return $new
}

proc fate {point tableau} {
    set current [value $point $tableau]
    set neighbours [sum_neighbours $point $tableau]
    return [expr {($neighbours == 3) || ($neighbours == 2 && $current == 1)}]
}

proc value {point tableau} {
    return [lindex $tableau {*}$point]
}

proc sum_neighbours {point tableau} {
    set sum 0
    foreach neighbour [get_neighbours $point] {
        incr sum [value $neighbour $tableau]
    }
    return $sum
}

proc get_neighbours {point} {
    lassign $point x y
    set results [list]
    foreach x_off {-1 0 1} {
        foreach y_off {-1 0 1} {
            if { ! ($x_off == 0 && $y_off == 0)} {
                set i [expr {$x + $x_off}]
                set j [expr {$y + $y_off}]
                if {(0 <= $i && $i < $::max_x) && (0 <= $j && $j < $::max_y)} {
                    lappend results [list $i $j]
                }
            }
        }
    }
    return $results
}

main


if test 3 -lt 5; then echo '3 is less than 5'; fi


factorial : Nat -> Nat
factorial x =
  if x == 0 then 1
  else
    x * fac (Nat.drop x 1)


#import std
#import nat

rule = -: ^(~&,~&l?(~&r-={2,3},~&r-={3})^|/~& [email protected])* pad0 iota512

neighborhoods = ~&thth3hthhttPCPthPTPTX**K7S+ swin3**+ [email protected]+ --<0>*+ 0-*

evolve "n" = next"n" rule**+ neighborhoods


[true]
  ['is true' puts]
  ['is false' puts]
ifte

=is true


Sub C_S_If()
Dim A$, B$

    A = "Hello"
    B = "World"
    'test
    If A = B Then Debug.Print A & " = " & B
    'other syntax
    If A = B Then
        Debug.Print A & " = " & B
    Else
        Debug.Print A & " and " & B & " are differents."
    End If
    'other syntax
    If A = B Then
        Debug.Print A & " = " & B
    Else: Debug.Print A & " and " & B & " are differents."
    End If
    'other syntax
    If A = B Then Debug.Print A & " = " & B _
    Else Debug.Print A & " and " & B & " are differents."
    'other syntax
    If A = B Then Debug.Print A & " = " & B Else Debug.Print A & " and " & B & " are differents."
    If A = B Then Debug.Print A & " = " & B Else: Debug.Print A & " and " & B & " are differents."
End Sub