_Title "Fractal Tree"
Const sw% = 640
Const sh% = 480

Screen _NewImage(sw, sh, 8)
Cls , 15: Color 2

Call tree(sw \ 2, sh - 10, _Pi * 1.5, _Pi / 180 * 29, 112, 15)

Sleep
System

Sub tree (x As Integer, y As Integer, initAngle As Double, theta As Double, length As Double, depth As Integer)
    Dim As Integer iL, newX, newY, iX, iY, iD
    iL = length: iX = x: iY = y: iD = depth
    newX = Cos(initAngle) * length + iX
    newY = Sin(initAngle) * length + iY
    Line (iX, iY)-(newX, newY)
    iL = length * .78
    iD = iD - 1
    If iD > 0 Then
        Call tree(newX, newY, initAngle - theta, theta, iL, iD)
        Call tree(newX, newY, initAngle + theta, theta, iL, iD)
    End If
End Sub


(ns rosettacode.adder
  (:use clojure.test))

(defn xor-gate [a b]
  (or (and a (not b)) (and b (not a))))

(defn half-adder [a b]
  "output: (S C)"
  (cons (xor-gate a b) (list (and a b))))

(defn full-adder [a b c]
  "output: (C S)"
  (let [HA-ca (half-adder c a)
        HA-ca->sb (half-adder (first HA-ca) b)]
    (cons (or (second HA-ca) (second HA-ca->sb))
          (list (first HA-ca->sb)))))

(defn n-bit-adder
  "first bits on the list are low order bits
1 = true
2 = false true
3 = true true
4 = false false true..."
  can add numbers of different bit-length
  ([a-bits b-bits] (n-bit-adder a-bits b-bits false))
  ([a-bits b-bits carry]
  (let [added (full-adder (first a-bits) (first b-bits) carry)]
    (if(and (nil? a-bits) (nil? b-bits))
      (if carry (list carry) '())
      (cons (second added) (n-bit-adder (next a-bits) (next b-bits) (first added)))))))

;use:
(n-bit-adder [true true true true true true] [true true true true true true])
=> (false true true true true true true)


[ $ "turtleduck.qky" loadfile ] now!

[ [ 1 1
    30 times
       [ tuck + ]
   swap join ] constant
   do ]                  is phi  (       --> n/d )

[ 2dup 5 1 v< iff
    2drop done
  2dup 5 1 v/
  proper 2drop wide
  2dup walk
  1 5 turn
  2dup phi v/
  2dup recurse
  -2 5 turn
  recurse
  1 5 turn
  -v fly ]               is tree ( n/d -->     )

turtle
-1 4 turn
-450 1 fly
500 1 tree


## Recursive FT plotting
plotftree <- function(x, y, a, d, c) {
x2=y2=0; d2r=pi/180.0; a1 <- a*d2r; d1=0;
if(d<=0) {return()}
if(d>0)
  { d1=d*10.0;
    x2=x+cos(a1)*d1;
    y2=y+sin(a1)*d1;
    segments(x*c, y*c, x2*c, y2*c, col='darkgreen');
    plotftree(x2,y2,a-20,d-1,c);
    plotftree(x2,y2,a+20,d-1,c);
    #return(2);
  }
}
## Plotting Fractal Tree. aev 3/27/17
## ord - order/depth, c - scale, xsh - x-shift, fn - file name,
##  ttl - plot title.
pFractalTree <- function(ord, c=1, xsh=0, fn="", ttl="") {
  cat(" *** START FRT:", date(), "\n");
  m=640;
  if(fn=="") {pf=paste0("FRTR", ord, ".png")} else {pf=paste0(fn, ".png")};
  if(ttl=="") {ttl=paste0("Fractal tree, order - ", ord)};
  cat(" *** Plot file -", pf, "title:", ttl, "\n");
  ##plot(NA, xlim=c(0,m), ylim=c(-m,0), xlab="", ylab="", main=ttl);
  plot(NA, xlim=c(0,m), ylim=c(0,m), xlab="", ylab="", main=ttl);
  plotftree(m/2+xsh,100,90,ord,c);
  dev.copy(png, filename=pf, width=m, height=m);
  dev.off(); graphics.off();
  cat(" *** END FRT:",date(),"\n");
}
## Executing:
pFractalTree(9);
pFractalTree(12,0.6,210);
pFractalTree(15,0.35,600);


#lang racket
(require graphics/turtles)

(define (tree n)
  (when (> n 1)
    (draw (/ n 2))
    (tprompt (split* (turn 60) (turn -60))
             (tree (/ n 2)))
    (draw (/ n 2))
    (turn 5)
    (tree (- n 1))))

(turtles #t) (move 100) (turn 90) (move -200)
(tree 35)
(save-turtle-bitmap "tree.png" 'png)


my ($width, $height) = (1000,1000); # image dimension
my $scale = 6/10; # branch scale relative to trunk
my $length = 400; # trunk size

say "<?xml version='1.0' encoding='utf-8' standalone='no'?>
<!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN'
'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'>
<svg width='100%' height='100%' version='1.1'
xmlns='http://www.w3.org/2000/svg'>";

tree($width/2, $height, $length, 3*pi/2);

say "</svg>";

multi tree($, $, $length where { $length < 1}, $) {}
multi tree($x, $y, $length, $angle)
{
	my ($x2, $y2) = ( $x + $length * $angle.cos, $y + $length * $angle.sin);
	say "<line x1='$x' y1='$y' x2='$x2' y2='$y2' style='stroke:rgb(0,0,0);stroke-width:1'/>";
	tree($x2, $y2, $length*$scale, $angle + pi/5);
	tree($x2, $y2, $length*$scale, $angle - pi/5);
}


       program-id. test-add.
       environment division.
       configuration section.
       special-names.
           class bin is "0" "1".
       data division.
       working-storage section.
       1 parms.
        2 a-in pic 9999.
        2 b-in pic 9999.
        2 r-out pic 9999.
        2 c-out pic 9.
       procedure division.
           display "Enter 'A' value (4-bits binary): "
               with no advancing
           accept a-in
           if a-in (1:) not bin
               display "A is not binary"
               stop run
           end-if
           display "Enter 'B' value (4-bits binary): "
               with no advancing
           accept b-in
           if b-in (1:) not bin
               display "B is not binary"
               stop run
           end-if
           call "add-4b" using parms
           display "Carry " c-out " result " r-out
           stop run
           .
       end program test-add.

       program-id. add-4b.
       data division.
       working-storage section.
       1 wk binary.
        2 i pic 9(4).
        2 occurs 5.
         3 a-reg pic 9.
         3 b-reg pic 9.
         3 c-reg pic 9.
         3 r-reg pic 9.
        2 a pic 9.
        2 b pic 9.
        2 c pic 9.
        2 a-not pic 9.
        2 b-not pic 9.
        2 c-not pic 9.
        2 ha-1s pic 9.
        2 ha-1c pic 9.
        2 ha-1s-not pic 9.
        2 ha-1c-not pic 9.
        2 ha-2s pic 9.
        2 ha-2c pic 9.
        2 fa-s pic 9.
        2 fa-c pic 9.
       linkage section.
       1 parms.
        2 a-in pic 9999.
        2 b-in pic 9999.
        2 r-out pic 9999.
        2 c-out pic 9.
       procedure division using parms.
           initialize wk
           perform varying i from 1 by 1
           until i > 4
               move a-in (5 - i:1) to a-reg (i)
               move b-in (5 - i:1) to b-reg (i)
           end-perform
           perform simulate-adder varying i from 1 by 1
               until i > 4
           move c-reg (5) to c-out
           perform varying i from 1 by 1
           until i > 4
               move r-reg (i) to r-out (5 - i:1)
           end-perform
           exit program
           .

       simulate-adder section.
           move a-reg (i) to a
           move b-reg (i) to b
           move c-reg (i) to c
           add a -1 giving a-not
           add b -1 giving b-not
           add c -1 giving c-not

           compute ha-1s = function max (
               function min ( a b-not )
               function min ( b a-not ) )
           compute ha-1c = function min ( a b )
           add ha-1s -1 giving ha-1s-not
           add ha-1c -1 giving ha-1c-not

           compute ha-2s = function max (
               function min ( c ha-1s-not )
               function min ( ha-1s c-not ) )
           compute ha-2c = function min ( c ha-1c )

           compute fa-s = ha-2s
           compute fa-c = function max ( ha-1c ha-2c )

           move fa-s to r-reg (i)
           move fa-c to c-reg (i + 1)
           .
       end program add-4b.


Red [Needs: 'View]

color: brown
width: 9
view/tight/options/flags/no-wait [	; click image to grow tree
	img: image 1097x617 draw [
		pen brown line-width 9 line 500x600 500x500] [grow]
] [offset: 0x0] [no-border]

ends: reduce [500x500 pi * 3 / 2]	; list of terminal nodes
da: pi * 30 / 180	; angle of branches in radians
ea: pi * 5 / 180	; offset added to angle to break symmetry

l: 200			; branches initial lenght
scale: 0.7		; branches scale factor
grow: does [		; grows branches
	l: l * scale
	color: 2 * color + leaf / 3
	width: width - 1
	newends: copy []
	foreach [p a] ends [
		a1: a + da - ea
		p1: p + as-pair l * cos a1 l * sin a1
		a2: a - da - ea
		p2: p + as-pair l * cos a2 l * sin a2
		append img/draw compose/deep [
			pen (color)	line-width (width) line (p1) (p) (p2)]
		append newends reduce [p1 a1 p2 a2]
	]
	ends: newends
]


load "guilib.ring"

new qapp
        {
        win1 = new qwidget() {
               setwindowtitle("drawing using qpainter")
               setgeometry(100,100,500,500)
               label1 = new qlabel(win1) {
                        setgeometry(10,10,400,400)
                        settext("")
               }
               draw()
               show()
         }
         exec()
         }

func draw
     p1 = new qpicture()
             color = new qcolor() {
             setrgb(0,0,255,255)
        }
        pen = new qpen() {
              setcolor(color)
              setwidth(1)
        }
        new qpainter() {
            begin(p1)
            setpen(pen)

        sizex = 400
        sizey = 200
        depth = 10

        tree(self, sizex, 0, sizey/2, 90, depth)

        endpaint()
        }
        label1 { setpicture(p1) show() }

        func tree myObj, x1, y1, size, angle, depth
             myObj{
             scale = 0.76
             spread = 25
             x2 = x1 + size * cos(angle)
             y2 = y1 + size * sin(angle)
             drawline(x1, y1, x2, y2)
             if depth > 0
             tree(self, x2, y2, size * scale, angle - spread, depth - 1)
             tree(self, x2, y2, size * scale, angle + spread, depth - 1) ok}


Shoes.app(:title => "Fractal Tree", :width => 600, :height => 600) do
  background "#fff"
  stroke "#000"
  @deg_to_rad = Math::PI / 180.0

  def drawTree(x1, y1, angle, depth)
    if depth != 0
      x2 = x1 + (Math.cos(angle * @deg_to_rad) * depth * 10.0).to_i
      y2 = y1 + (Math.sin(angle * @deg_to_rad) * depth * 10.0).to_i

      line x1, y1, x2, y2

      drawTree(x2, y2, angle - 20, depth - 1)
      drawTree(x2, y2, angle + 20, depth - 1)
    end
  end

  drawTree(300,550,-90,9)
end


with Ada.Text_IO,
     POSIX.Process_Identification,
     POSIX.Unsafe_Process_Primitives;

procedure Fork is
   use Ada.Text_IO,
       POSIX.Process_Identification,
       POSIX.Unsafe_Process_Primitives;
begin
   if Fork = Null_Process_ID then
      Put_Line ("This is the new process.");
   else
      Put_Line ("This is the original process.");
   end if;
exception
   when others =>
      Put_Line ("Something went wrong.");
end Fork;


# ATOMIC GATES
not_gate = (bit) ->
  [1, 0][bit]

and_gate = (bit1, bit2) ->
  bit1 and bit2

or_gate = (bit1, bit2) ->
  bit1 or bit2

# COMPOSED GATES
xor_gate = (A, B) ->
  X = and_gate A, not_gate(B)
  Y = and_gate not_gate(A), B
  or_gate X, Y

half_adder = (A, B) ->
  S = xor_gate A, B
  C = and_gate A, B
  [S, C]

full_adder = (C0, A, B) ->
  [SA, CA] = half_adder C0, A
  [SB, CB] = half_adder SA, B
  S = SB
  C = or_gate CA, CB
  [S, C]

n_bit_adder = (n) ->
  (A_bits, B_bits) ->
    s = []
    C = 0
    for i in [0...n]
      [S, C] = full_adder C, A_bits[i], B_bits[i]
      s.push S
    [s, C]

adder = n_bit_adder(4)
console.log adder [1, 0, 1, 0], [0, 1, 1, 0]


//Cargo deps :
//  piston = "0.35.0"
//  piston2d-graphics = "0.23.0"
//  piston2d-opengl_graphics = "0.49.0"
//  pistoncore-glutin_window = "0.42.0"

extern crate piston;
extern crate graphics;
extern crate opengl_graphics;
extern crate glutin_window;

use piston::window::WindowSettings;
use piston::event_loop::{Events, EventSettings};
use piston::input::RenderEvent;
use glutin_window::GlutinWindow as Window;
use opengl_graphics::{GlGraphics, OpenGL};
use graphics::{clear, line, Context};

const ANG: f64 = 20.0;
const COLOR: [f32; 4] = [1.0, 0.0, 0.5, 1.0];
const LINE_THICKNESS: f64 = 5.0;
const DEPTH: u32 = 11;

fn main() {
    let mut window: Window = WindowSettings::new("Fractal Tree", [1024, 768])
        .opengl(OpenGL::V3_2)
        .exit_on_esc(true)
        .build()
        .unwrap();
    let mut gl = GlGraphics::new(OpenGL::V3_2);

    let mut events = Events::new(EventSettings::new());
    while let Some(e) = events.next(&mut window) {
        if let Some(args) = e.render_args() {
            gl.draw(args.viewport(), |c, g| {
                clear([1.0, 1.0, 1.0, 1.0], g);
                draw_fractal_tree(512.0, 700.0, 0.0, DEPTH, c, g);
            });
        }
    }
}

fn draw_fractal_tree(x1: f64, y1: f64, angle: f64, depth: u32, c: Context, g: &mut GlGraphics) {
    let x2 = x1 + angle.to_radians().sin() * depth as f64 * 10.0;
    let y2 = y1 - angle.to_radians().cos() * depth as f64 * 10.0;
    line(
        COLOR,
        LINE_THICKNESS * depth as f64 * 0.2,
        [x1, y1, x2, y2],
        c.transform,
        g,
    );
    if depth > 0 {
        draw_fractal_tree(x2, y2, angle - ANG, depth - 1, c, g);
        draw_fractal_tree(x2, y2, angle + ANG, depth - 1, c, g);
    }
}


import swing._
import java.awt.{RenderingHints, BasicStroke, Color}

object FractalTree extends SimpleSwingApplication {
  val DEPTH = 9

  def top = new MainFrame {
    contents = new Panel {
      preferredSize = new Dimension(600, 500)

      override def paintComponent(g: Graphics2D) {
        draw(300, 460, -90, DEPTH)

        def draw(x1: Int, y1: Int, angle: Double, depth: Int) {
          if (depth > 0) {
            val x2 = x1 + (math.cos(angle.toRadians) * depth * 10).toInt
            val y2 = y1 + (math.sin(angle.toRadians) * depth * 10).toInt

            g.setColor(Color.getHSBColor(0.25f - depth * 0.125f / DEPTH, 0.9f, 0.6f))
            g.setStroke(new BasicStroke(depth))
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
            g.drawLine(x1, y1, x2, y2)

            draw(x2, y2, angle - 20, depth - 1)
            draw(x2, y2, angle + 20, depth - 1)
          }
        }
      }
    }
  }
}


    var pid = fork()
    switch (pid) {
    case <0:
        println ("fork error")
        break
    case 0:
        println ("child")
        break
    default:
        println ("parent")
        break
    }


main:
(
  INT pid;
  IF (pid:=fork)=0 THEN
    print("This is new process")
  ELIF pid>0 THEN
    print("This is the original process")
  ELSE
    print("ERROR: Something went wrong")
  FI
)


MsgBox, 4, Fork, Start another process?
IfMsgBox, Yes
    Run, %A_AhkPath% "%A_ScriptFullPath%"
MsgBox, 0, Fork, Stop this process.


' Fork
pid = FORK
IF pid = 0 THEN
    PRINT "I am the child, my PID is:", MYPID
    ENDFORK
ELIF pid > 0 THEN
    PRINT "I am the parent, pid of child:", pid
    REPEAT
        PRINT "Waiting for child to exit"
        SLEEP 50
    UNTIL REAP(pid)
ELSE
    PRINT "Error in fork"
ENDIF


@echo off

if "%1" neq "" goto %1 || echo Not a valid subroutine

echo Starting mySubroutine1
start "" "%~n0" mySubroutine1
echo.

echo Starting mySubroutine2 6 3
start "" "%~n0" mySubroutine2 6 3
echo.

echo Starting mySubroutine3
start "" "%~n0" mySubroutine3
echo.

:: We wait here for the subroutines to run, but they are running asynchronously
timeout /t 1

for /l %%i in (1,1,3) do (
	for /f "tokens=*" %%j in (output%%i.txt) do (
		set output%%i=%%j
		del output%%i.txt
	)
)
echo.
echo.
echo Return values
echo ----------------------------
echo mySubroutine1: %output1%
echo mySubroutine2: %output2%
echo mySubroutine3: %output3%

pause>nul
exit

:mySubroutine1
echo This is the result of subroutine1 > output1.txt
exit

:mySubroutine2
set /a result=%2+%3
echo %result% > output2.txt
exit

:mySubroutine3
echo mySubroutine1 hasn't been run > output3.txt
if exist output1.txt echo mySubroutine1 has been run > output3.txt
exit


;; returns a list of bits: '(sum carry)
(defun half-adder (a b)
  (list (logxor a b) (logand a b)))

;; returns a list of bits: '(sum, carry)
(defun full-adder (a b c-in)
  (let*
    ((h1 (half-adder c-in a))
    (h2 (half-adder (first h1) b)))
    (list (first h2) (logior (second h1) (second h2)))))

;; a and b are lists of 4 bits each
(defun 4-bit-adder (a b)
  (let*
    ((add-1 (full-adder (fourth a) (fourth b) 0))
      (add-2 (full-adder (third a) (third b) (second add-1)))
      (add-3 (full-adder (second a) (second b) (second add-2)))
      (add-4 (full-adder (first a) (first b) (second add-3))))
    (list
      (list (first add-4) (first add-3) (first add-2) (first add-1))
      (second add-4))))

(defun main ()
  (print (4-bit-adder (list 0 0 0 0) (list 0 0 0 0)))   ;; '(0 0 0 0) and 0
  (print (4-bit-adder (list 0 0 0 0) (list 1 1 1 1)))   ;; '(1 1 1 1) and 0
  (print (4-bit-adder (list 1 1 1 1) (list 0 0 0 0)))   ;; '(1 1 1 1) and 0
  (print (4-bit-adder (list 0 1 0 1) (list 1 1 0 0)))   ;; '(0 0 0 1) and 1
  (print (4-bit-adder (list 1 1 1 1) (list 1 1 1 1)))   ;; '(1 1 1 0) and 1
  (print (4-bit-adder (list 1 0 1 0) (list 0 1 0 1)))   ;; '(1 1 1 1) and 0
 )

(main)


(import (scheme base)
        (scheme file)
        (scheme inexact)
        (scheme write))

(define *scale* 10) ; controls overall size of tree
(define *split* 20) ; controls angle of split (in degrees)

;; construct lines for tree as list of 5-tuples (x1 y1 x2 y2 depth)
;; - x1 y1 is start point
;; - angle of this line, in radians
;; - depth, depth within tree (controls length of line)
(define (create-tree x1 y1 angle depth)
  (define (degrees->radians d)
    (let ((pi 3.14159265358979323846264338327950288419716939937510582097))
      (* d pi 1/180)))
  ;
  (if (zero? depth)
    '()
    (let ((x2 (+ x1 (* (cos (degrees->radians angle)) depth *scale*)))
          (y2 (+ y1 (* (sin (degrees->radians angle)) depth *scale*))))
      (append (list (map truncate (list x1 y1 x2 y2 depth)))
              (create-tree x2 y2 (- angle *split*) (- depth 1))
              (create-tree x2 y2 (+ angle *split*) (- depth 1))))))

;; output the tree to an eps file
(define (output-tree-as-eps filename tree)
  (when (file-exists? filename) (delete-file filename))
  (with-output-to-file
    filename
    (lambda ()
      (display "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 800 800\n")

      ;; add each line - sets linewidth based on depth in tree
      (for-each (lambda (line)
                  (display
                    (string-append "newpath\n"
                                   (number->string (list-ref line 0)) " "
                                   (number->string (list-ref line 1)) " "
                                   "moveto\n"
                                   (number->string (list-ref line 2)) " "
                                   (number->string (list-ref line 3)) " "
                                   "lineto\n"
                                   (number->string (truncate (/ (list-ref line 4) 2)))
                                   " setlinewidth\n"
                                   "stroke\n"
                                   )))
                tree)
      (display "\n%%EOF"))))

(output-tree-as-eps "fractal.eps" (create-tree 400 200 90 9))


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <err.h>

int main()
{
	pid_t pid;

	if (!(pid = fork())) {
		usleep(10000);
		printf("\tchild process: done\n");
	} else if (pid < 0) {
		err(1, "fork error");
	} else {
		printf("waiting for child %d...\n", (int)pid);
		printf("child %d finished\n", (int)wait(0));
	}

	return 0;
}


using System;
using System.Threading;

namespace Fork {
    class Program {
        static void Fork() {
            Console.WriteLine("Spawned Thread");
        }

        static void Main(string[] args) {
            Thread t = new Thread(new ThreadStart(Fork));
            t.Start();

            Console.WriteLine("Main Thread");
            t.Join();

            Console.ReadLine();
        }
    }
}


#include<iostream>
#include<unistd.h>

int main()
{
  pid_t pid = fork();

  if (pid == 0)
  {
    std::cout << "This is the new process\n";
  }
  else if (pid > 0)
  {
    std::cout << "This is the original process\n";
  }
  else
  {
    std::cerr << "ERROR: Something went wrong\n";
  }

  return 0;
}


import std.stdio, std.traits;

void fourBitsAdder(T)(in T a0, in T a1, in T a2, in T a3,
                      in T b0, in T b1, in T b2, in T b3,
                      out T o0, out T o1,
                      out T o2, out T o3,
                      out T overflow) pure nothrow @nogc {

    // A XOR using only NOT, AND and OR, as task requires.
    static T xor(in T x, in T y) pure nothrow @nogc {
        return (~x & y) | (x & ~y);
    }

    static void halfAdder(in T a, in T b,
                          out T s, out T c) pure nothrow @nogc {
        s = xor(a, b);
        // s = a ^ b; // The built-in D xor.
        c = a & b;
    }

    static void fullAdder(in T a, in T b, in T ic,
                          out T s, out T oc) pure nothrow @nogc {
        T ps, pc, tc;

        halfAdder(/*in*/a, b,   /*out*/ps, pc);
        halfAdder(/*in*/ps, ic, /*out*/s, tc);
        oc = tc | pc;
    }

    T zero, tc0, tc1, tc2;

    fullAdder(/*in*/a0, b0, zero, /*out*/o0, tc0);
    fullAdder(/*in*/a1, b1, tc0,  /*out*/o1, tc1);
    fullAdder(/*in*/a2, b2, tc1,  /*out*/o2, tc2);
    fullAdder(/*in*/a3, b3, tc2,  /*out*/o3, overflow);
}

void main() {
    alias T = size_t;
    static assert(isUnsigned!T);

    enum T one = T.max,
           zero = T.min,
           a0 = zero, a1 = one, a2 = zero, a3 = zero,
           b0 = zero, b1 = one, b2 = one,  b3 = one;
    T s0, s1, s2, s3, overflow;

    fourBitsAdder(/*in*/ a0, a1, a2, a3,
                  /*in*/ b0, b1, b2, b3,
                  /*out*/s0, s1, s2, s3, overflow);

    writefln("      a3 %032b", a3);
    writefln("      a2 %032b", a2);
    writefln("      a1 %032b", a1);
    writefln("      a0 %032b", a0);
    writefln("      +");
    writefln("      b3 %032b", b3);
    writefln("      b2 %032b", b2);
    writefln("      b1 %032b", b1);
    writefln("      b0 %032b", b0);
    writefln("      =");
    writefln("      s3 %032b", s3);
    writefln("      s2 %032b", s2);
    writefln("      s1 %032b", s1);
    writefln("      s0 %032b", s0);
    writefln("overflow %032b", overflow);
}


trunk = 1;                  //trunk length
ratio = 0.8;                //size ratio between two consecutive branches
depth = 9;                  //final number of branch levels
orign = 0;                  //origin of the tree (should be complex)
angle = 45*%pi/180;         //angle between two branches [rad]
trunk_angle = 90*%pi/180;   //angle between trunk and X-axis [rad]

right_angle = angle/2;      //angles to the right or to the left
left_angle = 0.8*angle;     //can be set independently or
                            //as function of 'angle'

//L-system definition:
//Alphabet: FBD[]+-
    //F: go forward             B: go backwards
    //[: start new branch       ]: end current branch
    //+: branch to the right    -: branch to the left
    //D: double line (forward then backward)
//Axiom:    D
//Rule:     D -> F[+D-D]B

//L-system sentence generation
sentence = 'D'
rule = 'F[+D-D]B';
for i=1:depth
    sentence = strsubst(sentence,'D',rule);
end
sentence = strsplit(sentence)';

//Empty tree
tree_size = 1.0...
            + length(find(sentence=='F'|sentence=='B'))...
            + 2 * length(find(sentence=='D'));
tree=zeros(tree_size,1);

//Drawing the tree
branch_level = 0;
curr_angle = trunk_angle;
curr_pos = 1;

for ind = 1:size(sentence,'c')
    charac = sentence(ind);

    select charac
        case 'F' then //Draw line forward
            tree(curr_pos+1) = tree(curr_pos)...
                               + trunk * ratio^branch_level * exp(curr_angle*%i);
            curr_pos = curr_pos + 1;

        case 'B' then //Draw line backwards
            tree(curr_pos+1) = tree(curr_pos)...
                               + trunk * ratio^branch_level * exp((%pi+curr_angle)*%i);
            curr_pos = curr_pos + 1;

        case '[' then //New branch
            branch_level = branch_level + 1;

        case '+' then //Turn right
            curr_angle = curr_angle - right_angle;

        case '-' then //Turn left
            curr_angle = curr_angle + right_angle + left_angle;

        case ']' then //End of branch
            branch_level = branch_level - 1;
            curr_angle = curr_angle - left_angle;

        case 'D' then //Double line
            tree(curr_pos+1) = tree(curr_pos)...
                               + trunk * ratio^branch_level * exp(curr_angle*%i);
            tree(curr_pos+2) = tree(curr_pos+1)...
                               + trunk * ratio^branch_level * exp((%pi+curr_angle)*%i);
            curr_pos = curr_pos + 2;
    end
end

scf(); clf();
xname('Fractal tree: '+string(depth)+' levels')
plot2d(real(tree),imag(tree),14);
set(gca(),'isoview','on');
set(gca(),'axes_visible',['off','off','off']);


$ include "seed7_05.s7i";
  include "float.s7i";
  include "math.s7i";
  include "draw.s7i";
  include "keybd.s7i";

const float: DEG_TO_RAD is PI / 180.0;

const proc: drawTree (in integer: x1, in integer: y1, in float: angle, in integer: depth) is func
  local
    var integer: x2 is 0;
    var integer: y2 is 0;
  begin
    if depth <> 0 then
      x2 := x1 + trunc(cos(angle * DEG_TO_RAD) * flt(depth * 10));
      y2 := y1 + trunc(sin(angle * DEG_TO_RAD) * flt(depth * 10));
      lineTo(x1, y1, x2, y2, white);
      drawTree(x2, y2, angle - 20.0, depth - 1);
      drawTree(x2, y2, angle + 20.0, depth - 1);
    end if;
  end func;

const proc: main is func
  begin
    screen(600, 500);
    clear(curr_win, black);
    KEYBOARD := GRAPH_KEYBOARD;
    drawTree(300, 470, -90.0, 9);
    ignore(getc(KEYBOARD));
  end func;


func tree(img, x, y, scale=6/10, len=400, angle=270) {

    len < 1 && return()

    img.moveTo(x, y)
    img.angle(angle)
    img.line(len)

    var (x1, y1) = img.curPos
    tree(img, x1, y1, scale, len*scale, angle+35)
    tree(img, x1, y1, scale, len*scale, angle-35)
}

require('GD::Simple')

var (width=1000, height=1000)
var img = %s|GD::Simple|.new(width, height)
img.fgcolor('black')
img.penSize(1, 1)

tree(img, width/2, height)

File('tree.png').write(img.png, :raw)


(require '[clojure.java.shell :as shell])
(shell/sh "echo" "foo") ; evaluates to {:exit 0, :out "foo\n", :err ""}


       identification division.
       program-id. forking.

       data division.
       working-storage section.
       01 pid usage binary-long.

       procedure division.
       display "attempting fork"

       call "fork" returning pid
           on exception
               display "error: no fork linkage" upon syserr
       end-call

       evaluate pid
          when = 0
              display "    child sleeps"
              call "C$SLEEP" using 3
              display "    child task complete"
          when < 0
              display "error: fork result not ok" upon syserr
          when > 0
              display "parent waits for child..."
              call "wait" using by value 0
              display "parental responsibilities fulfilled"
       end-evaluate

       goback.
       end program forking.


(let ((pid (sb-posix:fork)))
  (cond
   ((zerop pid) (write-line "This is the new process."))
   ((plusp pid) (write-line "This is the original process."))
   (t           (error "Something went wrong while forking."))))


import core.thread;
import std.stdio;

void main() {
    new Thread({
        writeln("Spawned thread.");
    }).start;
    writeln("Main thread.");
}


program Four_bit_adder;

{$APPTYPE CONSOLE}

uses
  System.SysUtils;

Type
  TBitAdderOutput = record
    S, C: Boolean;
    procedure Assign(_s, _C: Boolean);
    function ToString: string;
  end;

  TNibbleBits = array[1..4] of Boolean;

  TNibble = record
    Bits: TNibbleBits;
    procedure Assign(_Bits: TNibbleBits); overload;
    procedure Assign(value: byte); overload;
    function ToString: string;
  end;

  TFourBitAdderOutput = record
    N: TNibble;
    c: Boolean;
    procedure Assign(_c: Boolean; _N: TNibbleBits);
    function ToString: string;
  end;

  TLogic = record
    class function GateNot(const A: Boolean): Boolean; static;
    class function GateAnd(const A, B: Boolean): Boolean; static;
    class function GateOr(const A, B: Boolean): Boolean; static;
    class function GateXor(const A, B: Boolean): Boolean; static;
  end;

  TConstructiveBlocks = record
    function HalfAdder(const A, B: Boolean): TBitAdderOutput;
    function FullAdder(const A, B, CI: Boolean): TBitAdderOutput;
    function FourBitAdder(const A, B: TNibble; const CI: Boolean): TFourBitAdderOutput;
  end;

{ TBitAdderOutput }

procedure TBitAdderOutput.Assign(_s, _C: Boolean);
begin
  s := _s;
  c := _C;
end;

function TBitAdderOutput.ToString: string;
begin
  Result := 'S' + ord(s).ToString + 'C' + ord(c).ToString;
end;

{ TNibble }

procedure TNibble.Assign(_Bits: TNibbleBits);
var
  i: Integer;
begin
  for i := 1 to 4 do
    Bits[i] := _Bits[i];
end;

procedure TNibble.Assign(value: byte);
var
  i: Integer;
begin
  value := value and $0F;
  for i := 1 to 4 do
    Bits[i] := ((value shr (i - 1)) and 1) = 1;
end;

function TNibble.ToString: string;
var
  i: Integer;
begin
  Result := '';
  for i := 4 downto 1 do
    Result := Result + ord(Bits[i]).ToString;
end;

{ TFourBitAdderOutput }

procedure TFourBitAdderOutput.Assign(_c: Boolean; _N: TNibbleBits);
begin
  N.Assign(_N);
  c := _c;
end;

function TFourBitAdderOutput.ToString: string;
begin
  Result := N.ToString + ' c=' + ord(c).ToString;
end;

{ TLogic }

class function TLogic.GateAnd(const A, B: Boolean): Boolean;
begin
  Result := A and B;
end;

class function TLogic.GateNot(const A: Boolean): Boolean;
begin
  Result := not A;
end;

class function TLogic.GateOr(const A, B: Boolean): Boolean;
begin
  Result := A or B;
end;

class function TLogic.GateXor(const A, B: Boolean): Boolean;
begin
  Result := GateOr(GateAnd(A, GateNot(B)), (GateAnd(GateNot(A), B)));
end;

{ TConstructiveBlocks }

function TConstructiveBlocks.FourBitAdder(const A, B: TNibble; const CI: Boolean):
  TFourBitAdderOutput;
var
  FA: array[1..4] of TBitAdderOutput;
  i: Integer;
begin
  FA[1] := FullAdder(A.Bits[1], B.Bits[1], CI);
  Result.N.Bits[1] := FA[1].S;

  for i := 2 to 4 do
  begin
    FA[i] := FullAdder(A.Bits[i], B.Bits[i], FA[i - 1].C);
    Result.N.Bits[i] := FA[i].S;
  end;
  Result.C := FA[4].C;
end;

function TConstructiveBlocks.FullAdder(const A, B, CI: Boolean): TBitAdderOutput;
var
  HA1, HA2: TBitAdderOutput;
begin
  HA1 := HalfAdder(CI, A);
  HA2 := HalfAdder(HA1.S, B);
  Result.Assign(HA2.S, TLogic.GateOr(HA1.C, HA2.C));
end;

function TConstructiveBlocks.HalfAdder(const A, B: Boolean): TBitAdderOutput;
begin
  Result.Assign(TLogic.GateXor(A, B), TLogic.GateAnd(A, B));
end;

var
  j, k: Integer;
  A, B: TNibble;
  Blocks: TConstructiveBlocks;

begin
  for k := 0 to 255 do
  begin
    A.Assign(0);
    B.Assign(0);
    for j := 0 to 7 do
    begin
      if j < 4 then
        A.Bits[j + 1] := ((1 shl j) and k) > 0
      else
        B.Bits[j + 1 - 4] := ((1 shl j) and k) > 0;
    end;

    write(A.ToString, ' + ', B.ToString, ' = ');
    Writeln(Blocks.FourBitAdder(A, B, false).ToString);
  end;
  Writeln;
  Readln;
end.


Object subclass: #FractalTree
    instanceVariableNames: ''
    classVariableNames: ''
    poolDictionaries: ''
    category: 'RosettaCode'


<?xml version="1.0" standalone="yes"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"
 "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink"
     width="400" height="320">
  <style type="text/css"><![CDATA[
    line { stroke: black; stroke-width: .05; }
    circle { fill: black; }
  ]]></style>

<defs>
  <g id="stem"> <line x1="0" y1="0" x2="0" y2="-1"/> </g>

  <g id="l0"><use xlink:href="#stem"/></g>
  <!-- These are identical except for the id and href. -->
  <g id="l1"> <use xlink:href="#l0" transform="translate(0, -1) rotate(-35) scale(.7)"/>
              <use xlink:href="#l0" transform="translate(0, -1) rotate(+35) scale(.7)"/>
              <use xlink:href="#stem"/></g>
  <g id="l2"> <use xlink:href="#l1" transform="translate(0, -1) rotate(-35) scale(.7)"/>
              <use xlink:href="#l1" transform="translate(0, -1) rotate(+35) scale(.7)"/>
              <use xlink:href="#stem"/></g>
  <g id="l3"> <use xlink:href="#l2" transform="translate(0, -1) rotate(-35) scale(.7)"/>
              <use xlink:href="#l2" transform="translate(0, -1) rotate(+35) scale(.7)"/>
              <use xlink:href="#stem"/></g>
  <g id="l4"> <use xlink:href="#l3" transform="translate(0, -1) rotate(-35) scale(.7)"/>
              <use xlink:href="#l3" transform="translate(0, -1) rotate(+35) scale(.7)"/>
              <use xlink:href="#stem"/></g>
  <g id="l5"> <use xlink:href="#l4" transform="translate(0, -1) rotate(-35) scale(.7)"/>
              <use xlink:href="#l4" transform="translate(0, -1) rotate(+35) scale(.7)"/>
              <use xlink:href="#stem"/></g>
  <g id="l6"> <use xlink:href="#l5" transform="translate(0, -1) rotate(-35) scale(.7)"/>
              <use xlink:href="#l5" transform="translate(0, -1) rotate(+35) scale(.7)"/>
              <use xlink:href="#stem"/></g>
  <g id="l7"> <use xlink:href="#l6" transform="translate(0, -1) rotate(-35) scale(.7)"/>
              <use xlink:href="#l6" transform="translate(0, -1) rotate(+35) scale(.7)"/>
              <use xlink:href="#stem"/></g>
  <g id="l8"> <use xlink:href="#l7" transform="translate(0, -1) rotate(-35) scale(.7)"/>
              <use xlink:href="#l7" transform="translate(0, -1) rotate(+35) scale(.7)"/>
              <use xlink:href="#stem"/></g>
  <g id="l9"> <use xlink:href="#l8" transform="translate(0, -1) rotate(-35) scale(.7)"/>
              <use xlink:href="#l8" transform="translate(0, -1) rotate(+35) scale(.7)"/>
              <use xlink:href="#stem"/></g>
</defs>

<g transform="translate(200, 320) scale(100)">
  <use xlink:href="#l9"/>
</g>

</svg>


$! looper.com procedure
$ i = 10
$ loop:
$  show time
$  wait 'p1
$  i = i - 1
$  if i .gt. 0 then $  goto loop


program Fork_app;

{$APPTYPE CONSOLE}

uses
  System.Threading;

procedure Fork;
begin
  Writeln('Spawned Thread');
end;

var
  t: ITask;

begin
  t := TTask.Run(fork);

  Writeln('Main Thread');

  TTask.WaitForAll(t);
  Readln;
end.


defmodule Fork do
  def start do
    spawn(fn -> child end)
    IO.puts "This is the original process"
  end

  def child, do: IO.puts "This is the new process"
end

Fork.start


-module(fork).
-export([start/0]).

start() ->
    erlang:spawn( fun() -> child() end ),
    io:format("This is the original process~n").

child() ->
    io:format("This is the new process~n").


defmodule RC do
  use Bitwise
  @bit_size 4

  def four_bit_adder(a, b) do           # returns pair {sum, carry}
    a_bits = binary_string_to_bits(a)
    b_bits = binary_string_to_bits(b)
    Enum.zip(a_bits, b_bits)
    |> List.foldr({[], 0}, fn {a_bit, b_bit}, {acc, carry} ->
         {s, c} = full_adder(a_bit, b_bit, carry)
         {[s | acc], c}
       end)
  end

  defp full_adder(a, b, c0) do
    {s, c} = half_adder(c0, a)
    {s, c1} = half_adder(s, b)
    {s, bor(c, c1)}                     # returns pair {sum, carry}
  end

  defp half_adder(a, b) do
    {bxor(a, b), band(a, b)}            # returns pair {sum, carry}
  end

  def int_to_binary_string(n) do
    Integer.to_string(n,2) |> String.rjust(@bit_size, ?0)
  end

  defp binary_string_to_bits(s) do
    String.codepoints(s) |> Enum.map(fn bit -> String.to_integer(bit) end)
  end

  def task do
    IO.puts " A    B      A      B   C    S  sum"
    Enum.each(0..15, fn a ->
      bin_a = int_to_binary_string(a)
      Enum.each(0..15, fn b ->
        bin_b = int_to_binary_string(b)
        {sum, carry} = four_bit_adder(bin_a, bin_b)
        :io.format "~2w + ~2w = ~s + ~s = ~w ~s = ~2w~n",
            [a, b, bin_a, bin_b, carry, Enum.join(sum), Integer.undigits([carry | sum], 2)]
      end)
    end)
  end
end

RC.task


-module( four_bit_adder ).

-export( [add_bits/3, create/1, task/0] ).

add_bits( Adder, A_bits, B_bits ) ->
	Adder ! {erlang:self(), lists:reverse(A_bits), lists:reverse(B_bits)},
	receive
	{Adder, Sum, Carry} -> {Sum, Carry}
	end.

create( How_many_bits ) ->
	Full_adders = connect_full_adders( [full_adder_create() || _X <- lists:seq(1, How_many_bits)] ),
	erlang:spawn_link( fun() -> bit_adder_loop( Full_adders ) end ).

task() ->
	Adder = create( 4 ),
	add_bits( Adder, [0,0,1,0], [0,0,1,1] ).

bit_adder_loop( Full_adders ) ->
	receive
	{Pid, As, Bs} ->
		Sum = [full_adder_sum(Adder, A, B) || {Adder, A, B} <- lists:zip3(Full_adders, As, Bs)],
		Carry = receive
			{carry, C} -> C
			end,
		Pid ! {erlang:self(), lists:reverse(Sum), Carry},
		bit_adder_loop( Full_adders )
	end.

connect_full_adders( [Full_adder | T]=Full_adders ) ->
	lists:foldl( fun connect_full_adders/2, Full_adder, T ),
	Full_adders.

connect_full_adders( Full_adder, Previous_full_adder ) ->
	Previous_full_adder ! {carry_to, Full_adder},
	Full_adder.

half_adder( A, B ) -> {z_xor(A, B), A band B}.

full_adder( A, B, Carry ) ->
	{Sum1, Carry1} = half_adder( A, Carry),
	{Sum, Carry2} = half_adder( B, Sum1),
	{Sum, Carry1 bor Carry2}.

full_adder_create( ) -> erlang:spawn( fun() -> full_adder_loop({0, no_carry_pid}) end ).

full_adder_loop( {Carry, Carry_to} ) ->
	receive
	{carry, New_carry} -> full_adder_loop( {New_carry, Carry_to} );
	{carry_to, Pid} -> full_adder_loop( {Carry, Pid} );
	{add, Pid, A, B} ->
		{Sum, New_carry} = full_adder( A, B, Carry ),
		Pid ! {sum, erlang:self(), Sum},
		full_adder_loop_carry_pid( Carry_to, Pid ) ! {carry, New_carry},
		full_adder_loop( {New_carry, Carry_to} )
	end.

full_adder_loop_carry_pid( no_carry_pid, Pid ) -> Pid;
full_adder_loop_carry_pid( Pid, _Pid ) -> Pid.

full_adder_sum( Pid, A, B ) ->
	Pid ! {add, erlang:self(), A, B},
	receive
	{sum, Pid, S} -> S
	end.

%% xor exists, this is another implementation.
z_xor( A, B ) -> (A band (2+bnot B)) bor ((2+bnot A) band B).


extension CGFloat {
  func degrees_to_radians() -> CGFloat {
    return CGFloat(M_PI) * self / 180.0
  }
}

extension Double {
  func degrees_to_radians() -> Double {
    return Double(M_PI) * self / 180.0
  }
}

class Tree: UIView {

  func drawTree(x1: CGFloat, y1: CGFloat, angle: CGFloat, depth:Int){
    if depth == 0 {
      return
    }
    let ang = angle.degrees_to_radians()
    let x2:CGFloat = x1 + ( cos(ang) as CGFloat) * CGFloat(depth) * (self.frame.width / 60)
    let y2:CGFloat = y1 + ( sin(ang) as CGFloat) * CGFloat(depth) * (self.frame.width / 60)

    let line = drawLine(x1, y1: y1, x2: x2, y2: y2)

    line.stroke()
    drawTree(x2, y1: y2, angle: angle - 20, depth: depth - 1)
    drawTree(x2, y1: y2, angle: angle + 20, depth: depth - 1)
  }

  func drawLine(x1:CGFloat, y1:CGFloat, x2:CGFloat, y2:CGFloat) -> UIBezierPath
  {

    let path = UIBezierPath()
    path.moveToPoint(CGPoint(x: x1,y: y1))
    path.addLineToPoint(CGPoint(x: x2,y: y2))
    path.lineWidth = 1
    return path
  }

  override func drawRect(rect: CGRect) {

    let color = UIColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)
    color.set()
    drawTree(self.frame.width / 2 , y1: self.frame.height * 0.8, angle: -90 , depth: 9 )
  }
}

let tree = Tree(frame: CGRectMake(0, 0, 300, 300))
tree


open XWindows;
open Motif;

fun toI {x=x,y=y} = {x=Real.toInt  IEEEReal.TO_NEAREST x,y=Real.toInt  IEEEReal.TO_NEAREST y}  ;

fun drawOnTop win usegc ht hs {x=l1,y=l2} {x=r1,y=r2} =
 let
  val xy = {x=l1 - ht * (l2-r2) , y = l2 - ht * (r1-l1) }
  val zt = {x=r1 - ht * (l2-r2) , y=  r2 - ht * (r1-l1) }
  val ab = {x= ( (#x xy + #x zt) + hs * (#y zt - #y xy ) )/2.0 ,  y =  ( (#y zt + #y xy) - hs * (#x zt - #x xy )) /2.0 }
 in

  if abs (l1 - #x xy ) < 0.9 andalso abs (l2 - #y xy ) < 0.9
   then   XFlush (XtDisplay win)
   else
    (XFillPolygon (XtWindow win) usegc [ (XPoint o toI) {x=l1,y=l2},
                                         (XPoint o toI ) xy ,
				         (XPoint o toI ) ab ,
				         (XPoint o toI ) zt ,
				         (XPoint o toI ) {x=r1,y=r2} ] Convex CoordModeOrigin  ;
  drawOnTop win usegc (0.87*ht) hs xy ab ;
  drawOnTop win usegc (0.93*ht) hs ab zt )

end ;

val demoWindow = fn () =>
let
  val shell  =  XtAppInitialise       ""    "tree" "top" []  [ XmNwidth 800, XmNheight 650] ;
  val main   =  XmCreateMainWindow   shell    "main"         [ XmNmappedWhenManaged true ]  ;
  val canvas =  XmCreateDrawingArea  main   "drawarea"       [ XmNwidth 800, XmNheight 650] ;
  val usegc  =  DefaultGC (XtDisplay canvas) ;
in

  XtSetCallbacks   canvas [ (XmNexposeCallback ,
                               (fn (w,c,t) => ( drawOnTop canvas usegc 8.0 0.85 {x=385.0,y=645.0} {x=415.0,y=645.0} ; t) ) )
			  ] XmNarmCallback ;
   XtManageChild    canvas ;
   XtManageChild    main   ;
   XtRealizeWidget  shell

end ;

demoWindow ();


package require Tk

set SIZE	800
set SCALE	4.0
set BRANCHES	14
set ROTATION_SCALE 0.85
set INITIAL_LENGTH 50.0

proc draw_tree {w x y dx dy size theta depth} {
    global SCALE ROTATION_SCALE
    $w create line $x $y [expr {$x + $dx*$size}] [expr {$y + $dy*$size}]
    if {[incr depth -1] >= 0} {
	set x [expr {$x + $dx*$size}]
	set y [expr {$y + $dy*$size}]
	set ntheta [expr {$theta * $ROTATION_SCALE}]

	# Draw left branch
	draw_tree $w $x $y \
	    [expr {$dx*cos($theta) + $dy*sin($theta)}] \
	    [expr {$dy*cos($theta) - $dx*sin($theta)}] \
	    [expr {$size * (rand() + $SCALE - 1) / $SCALE}] $ntheta $depth
	# Draw right branch
	draw_tree $w $x $y \
	    [expr {$dx*cos(-$theta) + $dy*sin(-$theta)}] \
	    [expr {$dy*cos(-$theta) - $dx*sin(-$theta)}] \
	    [expr {$size * (rand() + $SCALE - 1) / $SCALE}] $ntheta $depth
    }
}

pack [canvas .c -width $SIZE -height $SIZE]
draw_tree .c [expr {$SIZE/2}] [expr {$SIZE-10}] 0.0 -1.0 $INITIAL_LENGTH \
    [expr {3.1415927 / 8}] $BRANCHES


USING: unix unix.process ;

[ "Hello form child" print flush 0 _exit ] [ drop "Hi from parent" print flush ] with-fork


#g
."Kezd!\n"
§child fork sto childpid
@childpid wait
@childpid ."child pid ez volt: " printnl
end
child: ."Én a child vagyok!\n"
#d 3.14 printnl
2 sleep
end
{ „childpid” }


Function script(s As String) As String
    Dim As String g = _
    "Set WshShell = WScript.CreateObject(""WScript.Shell"")" + _
    Chr(13,10) + "Return = WshShell.Run("""+s+" "",1,0)"
    Return g
End Function

Function guardaArchivo(nombreArchivo As String, p As String) As String
    Dim As Long n = Freefile
    If Open (nombreArchivo For Binary Access Write As #n) = 0 Then
        Put #n,,p
        Close
    Else
        Print "No se puede guardar " + nombreArchivo : Sleep : End
    End If
    Return nombreArchivo
End Function

Sub ejecutaScript(nombreArchivo As String)
    Shell "cscript.exe /Nologo " + nombreArchivo
End Sub

Var g = script("notepad.exe")  '<< ejecuta este .exe (notepad como demo)
guardaArchivo("script.vbs",g)
ejecutaScript("script.vbs")
Dim As String s
Print "Hola"
Input "Teclee algo: ", s
Print s
Kill "script.vbs"
Sleep


type Bit =
    | Zero
    | One

let bNot = function
    | Zero -> One
    | One -> Zero

let bAnd a b =
    match (a, b) with
    | (One, One) -> One
    | _ -> Zero

let bOr a b =
    match (a, b) with
    | (Zero, Zero) -> Zero
    | _ -> One

let bXor a b = bAnd (bOr a b) (bNot (bAnd a b))

let bHA a b = bAnd a b, bXor a b

let bFA a b cin =
    let (c0, s0) = bHA a b
    let (c1, s1) = bHA s0 cin
    (bOr c0 c1, s1)

let b4A (a3, a2, a1, a0) (b3, b2, b1, b0) =
    let (c1, s0) = bFA a0 b0 Zero
    let (c2, s1) = bFA a1 b1 c1
    let (c3, s2) = bFA a2 b2 c2
    let (c4, s3) = bFA a3 b3 c3
    (c4, s3, s2, s1, s0)

printfn "0001 + 0111 ="
b4A (Zero, Zero, Zero, One) (Zero, One, One, One) |> printfn "%A"


$$ MODE TUSCRIPT
dest="fracaltree.svg"
ERROR/STOP CREATE (dest,fdf-o,-std-)
ACCESS d: WRITE/ERASE/RECORDS/UTF8 $dest s,text
MODE DATA
$$ header=*
<?xml version="1.0" standalone="yes"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"
 "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg xmlns="http://www.w3.org/2000/svg"
 xmlns:xlink="http://www.w3.org/1999/xlink"
 width="400" height="320">
  <style type="text/css"><![CDATA[
  line { stroke: brown; stroke-width: .05; }
  ]]></style>
$$ WRITE/NEXT d header
$$ defsbeg=*
<defs>
  <g id="stem"> <line x1="0" y1="0" x2="0" y2="-1"/> </g>
  <g id="l"><use xlink:href="#stem"/></g>
$$ WRITE/NEXT d defsbeg
$$ LOOP n=10,21
$$ id=n+1,lastnr=VALUE(n)
$$ g=*
  <g id="{id}"> <use xlink:href="#{n}" transform="translate(0, -1) rotate(-35) scale(.7)"/>
  <use xlink:href="#{n}" transform="translate(0, -1) rotate(+35) scale(.7)"/> <use xlink:href="#stem"/></g>
$$ WRITE/NEXT d g
$$ ENDLOOP
$$ defsend = *
</defs>
<g transform="translate(200, 320) scale(100)">
  <use xlink:href="#{lastnr}"/>
</g>
$$ MODE TUSCRIPT
WRITE/NEXT d defsend
WRITE/NEXT d "</svg>"
ENDACCESS d


// Set up canvas for drawing
var canvas: HTMLCanvasElement = document.createElement('canvas')
canvas.width = 600
canvas.height = 500
document.body.appendChild(canvas)
var ctx: CanvasRenderingContext2D = canvas.getContext('2d')
ctx.fillStyle = '#000'
ctx.lineWidth = 1

// constants
const degToRad: number = Math.PI / 180.0
const totalDepth: number = 9

/** Helper function that draws a line on the canvas */
function drawLine(x1: number, y1: number, x2: number, y2: number): void {
    ctx.moveTo(x1, y1)
    ctx.lineTo(x2, y2)
}

/** Draws a branch at the given point and angle and then calls itself twice */
function drawTree(x1: number, y1: number, angle: number, depth: number): void {
    if (depth !== 0) {
        let x2: number = x1 + (Math.cos(angle * degToRad) * depth * 10.0)
        let y2: number = y1 + (Math.sin(angle * degToRad) * depth * 10.0)
        drawLine(x1, y1, x2, y2)
        drawTree(x2, y2, angle - 20, depth - 1)
        drawTree(x2, y2, angle + 20, depth - 1)
    }
}

// actual drawing of tree
ctx.beginPath()
drawTree(300, 500, -90, totalDepth)
ctx.closePath()
ctx.stroke()


package main

import (
    "fmt"
    "os"
)

func main() {
    fmt.Printf("PID: %v\n", os.Getpid())
    if len(os.Args) < 2 {
        fmt.Println("Done.")
        return
    }
    cp, err := os.StartProcess(os.Args[0], nil,
        &os.ProcAttr{Files: []*os.File{nil, os.Stdout}},
    )
    if err != nil {
        fmt.Println(err)
    }
    // Child process running independently at this point.
    // We have its PID and can print it.
    fmt.Printf("Child's PID: %v\n", cp.Pid)
    if _, err = cp.Wait(); err != nil {
        fmt.Println(err)
    }
}


println "BEFORE PROCESS"
Process p = Runtime.runtime.exec('''
C:/cygwin/bin/sh -c "
/usr/bin/date +'BEFORE LOOP: %T';
for i in 1 2 3 4 ; do
    /usr/bin/sleep 1;
    /usr/bin/echo \$i;
done;
/usr/bin/date +'AFTER LOOP: %T'"
''')
p.consumeProcessOutput(System.out, System.err)
(0..<8).each {
    Thread.sleep(500)
    print '.'
}
p.waitFor()
println "AFTER PROCESS"


import System.Posix.Process

main = do
  forkProcess (putStrLn "This is the new process")
  putStrLn "This is the original process"


: "NOT" invert 1 and ;
: "XOR" over over "NOT" and >r swap "NOT" and r> or ;
: halfadder over over and >r "XOR" r> ;
: fulladder halfadder >r swap halfadder r> or ;

: 4bitadder                            ( a3 a2 a1 a0 b3 b2 b1 b0 -- r3 r2 r1 r0 c)
  4 roll 0  fulladder swap >r >r
  3 roll r> fulladder swap >r >r
  2 roll r> fulladder swap >r fulladder r> r> r> 3 roll
;

: .add4 4bitadder 0 .r 4 0 do i 3 - abs roll 0 .r loop cr ;


module logic
  implicit none

contains

function xor(a, b)
  logical :: xor
  logical, intent(in) :: a, b

  xor = (a .and. .not. b) .or. (b .and. .not. a)
end function xor

function halfadder(a, b, c)
  logical :: halfadder
  logical, intent(in)  :: a, b
  logical, intent(out) :: c

  halfadder = xor(a, b)
  c = a .and. b
end function halfadder

function fulladder(a, b, c0, c1)
  logical :: fulladder
  logical, intent(in)  :: a, b, c0
  logical, intent(out) :: c1
  logical :: c2, c3

  fulladder = halfadder(halfadder(c0, a, c2), b, c3)
  c1 = c2 .or. c3
end function fulladder

subroutine fourbitadder(a, b, s)
  logical, intent(in)  :: a(0:3), b(0:3)
  logical, intent(out) :: s(0:4)
  logical :: c0, c1, c2

  s(0) = fulladder(a(0), b(0), .false., c0)
  s(1) = fulladder(a(1), b(1), c0, c1)
  s(2) = fulladder(a(2), b(2), c1, c2)
  s(3) = fulladder(a(3), b(3), c2, s(4))
end subroutine fourbitadder
end module

program Four_bit_adder
  use logic
  implicit none

  logical, dimension(0:3) :: a, b
  logical, dimension(0:4) :: s
  integer, dimension(0:3) :: ai, bi
  integer, dimension(0:4) :: si
  integer :: i, j

  do i = 0, 15
    a(0) = btest(i, 0); a(1) = btest(i, 1); a(2) = btest(i, 2); a(3) = btest(i, 3)
    where(a)
      ai = 1
    else where
      ai = 0
    end where
    do j = 0, 15
      b(0) = btest(j, 0); b(1) = btest(j, 1); b(2) = btest(j, 2); b(3) = btest(j, 3)
      where(b)
        bi = 1
      else where
        bi = 0
      end where
      call fourbitadder(a, b, s)
      where (s)
        si = 1
      elsewhere
        si = 0
      end where
      write(*, "(4i1,a,4i1,a,5i1)") ai(3:0:-1), " + ", bi(3:0:-1), " = ", si(4:0:-1)
    end do
  end do
end program


import "graphics" for Canvas, Color
import "dome" for Window
import "math" for Math

var Radians = Fn.new { |d| d * Num.pi / 180 }

class FractalTree {
    construct new(width, height) {
        Window.title = "Fractal Tree"
        Window.resize(width, height)
        Canvas.resize(width, height)
        _fore = Color.white
    }

    init() {
        drawTree(400, 500, -90, 9)
    }

    drawTree(x1, y1, angle, depth) {
        if (depth == 0) return
        var r = Radians.call(angle)
        var x2 = x1 + (Math.cos(r) * depth * 10).truncate
        var y2 = y1 + (Math.sin(r) * depth * 10).truncate
        Canvas.line(x1, y1, x2, y2, _fore)
        drawTree(x2, y2, angle - 20, depth - 1)
        drawTree(x2, y2, angle + 20, depth - 1)
    }

    update() {}

    draw(alpha) {}
}

var Game = FractalTree.new(800, 600)


SYSTEM( RUN )

WRITE(Messagebox='?Y', IOStat=ios) "Another Fork?"
IF(ios == 2) ALARM(999) ! quit immediately

! assume this script is stored as 'Fork.hic'
SYSTEM(SHell='Fork.hic')

BEEP("c e g 'c")
WRITE(Messagebox="!") "Waiting ..."
ALARM(999)              ! quit immediately


procedure main()
   if (fork()|runerr(500)) = 0 then
      write("child")
   else {
      delay(1000)
      write("parent")
   }
end


import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class RFork {

  public static void main(String[] args) {
    ProcessBuilder pb;
    Process pp;
    List<String> command;
    Map<String, String> env;
    BufferedReader ir;
    String currentuser;
    String line;
    try {
      command = Arrays.asList("");
      pb = new ProcessBuilder(command);
      env = pb.environment();
      currentuser = env.get("USER");
      command = Arrays.asList("ps", "-f", "-U", currentuser);
      pb.command(command);
      pp = pb.start();
      ir = new BufferedReader(new InputStreamReader(pp.getInputStream()));
      line = "Output of running " + command.toString() + " is:";
      do {
        System.out.println(line);
      } while ((line = ir.readLine()) != null);
    }
    catch (IOException iox) {
      iox.printStackTrace();
    }

    return;
  }
}


sub half_add( byval a as ubyte, byval b as ubyte,_
              byref s as ubyte, byref c as ubyte)
    s = a xor b
    c = a and b
end sub

sub full_add( byval a as ubyte, byval b as ubyte, byval c as ubyte,_
              byref s as ubyte, byref g as ubyte )
    dim as ubyte x, y, z
    half_add( a, c, x, y )
    half_add( x, b, s, z )
    g = y or z
end sub

sub fourbit_add( byval a3 as ubyte, byval a2 as ubyte, byval a1 as ubyte, byval a0 as ubyte,_
                 byval b3 as ubyte, byval b2 as ubyte, byval b1 as ubyte, byval b0 as ubyte,_
                 byref s3 as ubyte, byref s2 as ubyte, byref s1 as ubyte, byref s0 as ubyte,_
                 byref carry as ubyte )
    dim as ubyte c2, c1, c0
    full_add(a0, b0,  0, s0, c0)
    full_add(a1, b1, c0, s1, c1)
    full_add(a2, b2, c1, s2, c2)
    full_add(a3, b3, c2, s3, carry )
end sub

dim as ubyte s3, s2, s1, s0, carry

print "1100 + 0011 = ";
fourbit_add( 1, 1, 0, 0,  0, 0, 1, 1,  s3, s2, s1, s0, carry )
print carry;s3;s2;s1;s0

print "1111 + 0001 = ";
fourbit_add( 1, 1, 1, 1,  0, 0, 0, 1,  s3, s2, s1, s0, carry )
print carry;s3;s2;s1;s0

print "1111 + 1111 = ";
fourbit_add( 1, 1, 1, 1,  1, 1, 1, 1,  s3, s2, s1, s0, carry )
print carry;s3;s2;s1;s0


include c:\cxpl\codes;

proc DrawBranch(Lev, Dir, Len, X, Y);
int  Lev; real Dir, Len; int X, Y;
int  Red, Grn;
[Move(X, Y);
X:= X + fix(Len*Cos(Dir));
Y:= Y + fix(Len*Sin(Dir));
Red:= 255-Lev*8;  Grn:= Lev*12+100;
Line(X, Y, Red<<16+Grn<<8);
if Lev < 12 then                \limit level of recursion
        [DrawBranch(Lev+1, Dir-0.4, Len*0.8, X, Y);     \left
         DrawBranch(Lev+1, Dir+0.1, Len*0.8, X, Y);     \right
        ];
];

[SetVid($112);                  \set 640x480x24 video graphics mode
DrawBranch(0, -3.14159/2.0, 80.0, 360, 460);
if ChIn(1) then [];             \wait for keystroke
SetVid(3);                      \restore normal text mode
]


fcn fractalTree(){
   scale:=0.76;
   sizeX:=400; sizeY:=300;
   bitmap:=PPM(sizeX*2,sizeY*2,0xFF|FF|FF);
   branch:='wrap(x1,y1,size,angle,depth){
      ar:=angle.toRad();
      x2:=x1 - size*ar.cos();
      y2:=y1 + size*ar.sin();
      color:=(0xff-depth*8).shiftLeft(16) + (depth*12+100).shiftLeft(8);
      bitmap.line(x1,y1, x2,y2, color);
      if(depth){
         self.fcn(x2,y2,scale*size,angle - 30,depth - 1,vm.pasteArgs(5));
	 self.fcn(x2,y2,scale*size,angle + 8, depth - 1,vm.pasteArgs(5));
      }
   };
   branch(sizeX,0,sizeY/2,90.0,10);
   bitmap.write(File("foo.ppm","wb"));
}();


10 LET level=12: LET LONG=45
20 LET x=127: LET y=0
30 LET rotation=PI/2
40 LET a1=PI/9: LET a2=PI/9
50 LET c1=0.75: LET c2=0.75
60 DIM x(level): DIM y(level)
70 BORDER 0: PAPER 0: INK 4: CLS
80 GO SUB 100
90 STOP
100 REM Tree
110 LET x(level)=x: LET y(level)=y
120 GO SUB 1000
130 IF level=1 THEN GO TO 240
140 LET level=level-1
150 LET LONG=LONG*c1
160 LET rotation=rotation-a1
170 GO SUB 100
180 LET LONG=LONG/c1*c2
190 LET rotation=rotation+a1+a2
200 GO SUB 100
210 LET rotation=rotation-a2
220 LET LONG=LONG/c2
230 LET level=level+1
240 LET x=x(level): LET y=y(level)
250 RETURN
1000 REM Draw
1010 LET yn=-SIN rotation*LONG+y
1020 LET xn=COS rotation*LONG+x
1030 PLOT x,y: DRAW xn-x,y-yn
1040 LET x=xn: LET y=yn
1050 RETURN


println("Parent running.")
@async(begin sleep(1); println("This is the child process."); sleep(2); println("Child again.") end)
sleep(2)
println("This is the parent process again.")
sleep(2)
println("Parent again.")


// version 1.1.51

import java.io.InputStreamReader
import java.io.BufferedReader
import java.io.IOException

fun main(args: Array<String>) {
    try {
        val pb = ProcessBuilder()
        val currentUser = pb.environment().get("USER")
        val command = listOf("ps", "-f", "U", currentUser)
        pb.command(command)
        val proc = pb.start()
        val isr = InputStreamReader(proc.inputStream)
        val br = BufferedReader(isr)
        var line: String? = "Output of running $command is:"
        while(true) {
            println(line)
            line = br.readLine()
            if (line == null) break
        }
    }
    catch (iox: IOException) {
        iox.printStackTrace()
    }
}


local(mydata = 'I am data one')

split_thread => {
	loop(2)	=> {
		sleep(2000)
		stdoutnl(#mydata)
		#mydata = 'Oh, looks like I am in a new thread'
	}
}

loop(2)	=> {
	sleep(3000)
	stdoutnl(#mydata)
	#mydata = 'Aha, I am still in the original thread'
}


(defun start ()
  (spawn (lambda () (child))))

(defun child ()
  (lfe_io:format "This is the new process~n" '()))


local posix = require 'posix'

local pid = posix.fork()
if pid == 0 then
    print("child process")
elseif pid > 0 then
    print("parent process")
else
    error("unable to fork")
end


commandstring =  First[$CommandLine] <> " -noprompt -run \"Put[Factorial[20],ToFileName[$TemporaryDirectory,ToString[temp1]]];Quit[]\""
->"MathKernel -noprompt -run \"Put[Factorial[20],ToFileName[$TemporaryDirectory,ToString[temp1]]];Quit[]\""

Run[commandstring]
->0


/* NetRexx */
options replace format comments java crossref symbols binary

runSample(arg)
return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static

  do
    pb = ProcessBuilder([String ''])
    env = pb.environment()
    currentuser = String env.get('USER')
    command = Arrays.asList([String 'ps', '-f', '-U', currentuser])
    pb.command(command)
    pp = pb.start()
    ir = BufferedReader(InputStreamReader(pp.getInputStream()))
    line = String 'Output of running' command.toString() 'is:'
    loop label w_ until line = null
      say line
      line = ir.readLine()
      end w_
  catch iox = IOException
    iox.printStackTrace()
  end

  return


(let (pid (fork (println "Hello from child")))
  (cond
   ((nil? pid) (throw-error "Unable to fork"))
   ('t (wait-pid pid))))


package main

import "fmt"

func xor(a, b byte) byte {
    return a&(^b) | b&(^a)
}

func ha(a, b byte) (s, c byte) {
    return xor(a, b), a & b
}

func fa(a, b, c0 byte) (s, c1 byte) {
    sa, ca := ha(a, c0)
    s, cb := ha(sa, b)
    c1 = ca | cb
    return
}

func add4(a3, a2, a1, a0, b3, b2, b1, b0 byte) (v, s3, s2, s1, s0 byte) {
    s0, c0 := fa(a0, b0, 0)
    s1, c1 := fa(a1, b1, c0)
    s2, c2 := fa(a2, b2, c1)
    s3, v = fa(a3, b3, c2)
    return
}

func main() {
    // add 10+9  result should be 1 0 0 1 1
    fmt.Println(add4(1, 0, 1, 0, 1, 0, 0, 1))
}


import posix

var pid = fork()
if pid < 0:
    echo "Error forking a child"
elif pid > 0:
    echo "This is the parent process and its child has id ", pid, '.'
    # Further parent stuff.
else:
    echo "This is the child process."
    # Further child stuff.


#load "unix.cma";;
let pid = Unix.fork ();;
if pid > 0 then
  print_endline "This is the original process"
else
  print_endline "This is the new process";;


sub=.fork~new
sub~sub
Call syssleep 1
Do 3
  Say 'program   ' time()
  Call syssleep 1
  End

::class fork
:: method sub
Reply
Do 6
  Say 'subroutine' time()
  Call syssleep 1
  End


declare
  ParentVar1 = "parent data"
  ParentVar2

  functor RemoteCode
  export
     result:Result
  import QTk at 'x-oz://system/wp/QTk.ozf'
  define
     Result
     %% Show a simple window. When it is closed by the user, set Result.
     Window =
     {QTk.build
      td(action:proc {$} Result = 42 end %% on close
         label(text:"In child process: "#ParentVar1))} %% read parent process variable
     {Window show}
     !ParentVar2 = childData %% write to parent process variable
     {Wait Result}
  end

  %% create a new process on the same machine
  RM = {New Remote.manager init(host:localhost)}
  %% execute the code encapsulated in the given functor
  RemoteModule = {RM apply(RemoteCode $)}
in
  %% retrieve data from child process
  {Show RemoteModule.result} %% prints 42
  %% exit child process
  {RM close}
  {Show ParentVar2} %% print "childData"


class Main {
    static void main(args) {

        def bit1, bit2, bit3, bit4, carry

        def fourBitAdder = new FourBitAdder(
                { value -> bit1 = value },
                { value -> bit2 = value },
                { value -> bit3 = value },
                { value -> bit4 = value },
                { value -> carry = value }
        )

        // 5 + 6 = 11

        // 0101 i.e. 5
        fourBitAdder.setNum1Bit1 false
        fourBitAdder.setNum1Bit2 true
        fourBitAdder.setNum1Bit3 false
        fourBitAdder.setNum1Bit4 true

        // 0110 i.e 6
        fourBitAdder.setNum2Bit1 false
        fourBitAdder.setNum2Bit2 true
        fourBitAdder.setNum2Bit3 true
        fourBitAdder.setNum2Bit4 false

        def boolToInt = { bool ->
            bool ? 1 : 0
        }

        println ("0101 + 0110 = ${boolToInt(bit1)}${boolToInt(bit2)}${boolToInt(bit3)}${boolToInt(bit4)}")
    }
}

class Not {
    Closure output

    Not(output) {
        this.output = output
    }

    def setInput(input) {
        output !input
    }
}

class And {
    boolean input1
    boolean input2
    Closure output

    And(output) {
        this.output = output
    }

    def setInput1(input) {
        this.input1 = input
        output(input1 && input2)
    }

    def setInput2(input) {
        this.input2 = input
        output(input1 && input2)
    }
}

class Nand {
    And andGate
    Not notGate

    Nand(output) {
        notGate = new Not(output)
        andGate = new And({ value ->
            notGate.setInput value
        })
    }

    def setInput1(input) {
        andGate.setInput1 input
    }

    def setInput2(input) {
        andGate.setInput2 input
    }
}

class Or {
    Not firstInputNegation
    Not secondInputNegation
    Nand nandGate

    Or(output) {
        nandGate = new Nand(output)
        firstInputNegation = new Not({ value ->
            nandGate.setInput1 value
        })
        secondInputNegation = new Not({ value ->
            nandGate.setInput2 value
        })
    }

    def setInput1(input) {
        firstInputNegation.setInput input
    }

    def setInput2(input) {
        secondInputNegation.setInput input
    }
}

class Xor {
    And andGate
    Or orGate
    Nand nandGate

    Xor(output) {
        andGate = new And(output)
        orGate = new Or({ value ->
            andGate.setInput1 value
        })
        nandGate = new Nand({ value ->
            andGate.setInput2 value
        })

    }

    def setInput1(input) {
        orGate.setInput1 input
        nandGate.setInput1 input
    }

    def setInput2(input) {
        orGate.setInput2 input
        nandGate.setInput2 input
    }
}

class Adder {
    Or orGate
    Xor xorGate1
    Xor xorGate2
    And andGate1
    And andGate2

    Adder(sumOutput, carryOutput) {
        xorGate1 = new Xor(sumOutput)
        orGate = new Or(carryOutput)
        andGate1 = new And({ value ->
            orGate.setInput1 value
        })
        xorGate2 = new Xor({ value ->
            andGate1.setInput1 value
            xorGate1.setInput1 value
        })
        andGate2 = new And({ value ->
            orGate.setInput2 value
        })
    }

    def setBit1(input) {
        xorGate2.setInput1 input
        andGate2.setInput2 input
    }

    def setBit2(input) {
        xorGate2.setInput2 input
        andGate2.setInput1 input
    }

    def setCarry(input) {
        andGate1.setInput2 input
        xorGate1.setInput2 input
    }
}

class FourBitAdder {
    Adder adder1
    Adder adder2
    Adder adder3
    Adder adder4

    FourBitAdder(bit1, bit2, bit3, bit4, carry) {
        adder1 = new Adder(bit1, carry)
        adder2 = new Adder(bit2, { value ->
            adder1.setCarry value
        })
        adder3 = new Adder(bit3, { value ->
            adder2.setCarry value
        })
        adder4 = new Adder(bit4, { value ->
            adder3.setCarry value
        })
    }

    def setNum1Bit1(input) {
        adder1.setBit1 input
    }

    def setNum1Bit2(input) {
        adder2.setBit1 input
    }

    def setNum1Bit3(input) {
        adder3.setBit1 input
    }

    def setNum1Bit4(input) {
        adder4.setBit1 input
    }

    def setNum2Bit1(input) {
        adder1.setBit2 input
    }

    def setNum2Bit2(input) {
        adder2.setBit2 input
    }

    def setNum2Bit3(input) {
        adder3.setBit2 input
    }

    def setNum2Bit4(input) {
        adder4.setBit2 input
    }
}


void
foo()
{
  if (pari_daemon())
    pari_printf("Original\n");
  else
    pari_printf("Fork\n");
}


FORK:
if ($pid = fork()) {
    # parent code
} elsif (defined($pid)) {
    setsid; # tells apache to let go of this process and let it run solo
    # disconnect ourselves from input, output, and errors
    close(STDOUT);
    close(STDIN);
    close(STDERR);
    # re-open to /dev/null to prevent irrelevant warn messages.
    open(STDOUT, '>/dev/null');
    open(STDIN, '>/dev/null');
    open(STDERR, '>>/home/virtual/logs/err.log');

    # child code

    exit; # important to exit
} elsif($! =~ /emporar/){
    warn '[' . localtime() . "] Failed to Fork - Will try again in 10 seconds.\n";
    sleep(10);
    goto FORK;
} else {
    warn '[' . localtime() . "] Unable to fork - $!";
    exit(0);
}


without js
procedure mythread()
    ?"mythread"
    exit_thread(0)
end procedure

atom hThread = create_thread(routine_id("mythread"),{})
?"main carries on"
wait_thread(hThread)


import Control.Arrow
import Data.List (mapAccumR)

bor, band :: Int -> Int -> Int
bor = max
band = min
bnot :: Int -> Int
bnot = (1-)


#
# 4bitadder.icn, emulate a 4 bit adder. Using only and, or, not
#
record carry(c)

#
# excercise the adder, either "test" or 2 numbers
#
procedure main(argv)
    c := carry(0)

    # cli test
    if map(\argv[1]) == "test" then {
        # Unicon allows explicit radix literals
        every i := (2r0000  | 2r1001 | 2r1111) do {
            write(i, "+0,3,9,15")
            every j := (0 | 3 | 9 | 15) do {
                ans := fourbitadder(t1 := fourbits(i), t2 := fourbits(j), c)
                write(t1, " + ", t2, " = ", c.c, ":", ans)
            }
        }
        return
    }
    # command line, two values, if given, first try four bit binaries
    cli := fourbitadder(t1 := (*\argv[1] = 4 & fourbits("2r" || argv[1])),
                        t2 := (*\argv[2] = 4 & fourbits("2r" || argv[2])), c)
    write(t1, " + ", t2, " = ", c.c, ":", \cli) & return

    # if no result for that, try decimal values
    cli := fourbitadder(t1 := fourbits(\argv[1]),
                        t2 := fourbits(\argv[2]), c)
    write(t1, " + ", t2, " = ", c.c, ":", \cli) & return

    # or display the help
    write("Usage: 4bitadder [\"test\"] | [bbbb bbbb] | [n n], range 0-15")
end

#
# integer to fourbits as string
#
procedure fourbits(i)
    local s, t
    if not numeric(i) then fail
    if not (0 <= integer(i) < 16) then {
        write("out of range: ", i)
        fail
    }
    s := ""
    every t := (8 | 4 | 2 | 1) do {
        s ||:= if iand(i, t) ~= 0 then "1" else "0"
    }
    return s
end

#
# low level xor emulation with or, and, not
#
procedure xor(a, b)
    return ior(iand(a, icom(b)), iand(b, icom(a)))
end

#
# half adder, and into carry, xor for result bit
#
procedure halfadder(a, b, carry)
    carry.c := iand(a,b)
    return xor(a,b)
end

#
# full adder, two half adders, or for carry
#
procedure fulladder(a, b, c0, c1)
    local c2, c3, r
    c2 := carry(0)
    c3 := carry(0)

    # connect two half adders with carry
    r := halfadder(halfadder(c0.c, a, c2), b, c3)
    c1.c := ior(c2.c, c3.c)
    return r
end

#
# fourbit adder, as bit string
#
procedure fourbitadder(a, b, cr)
    local cs, c0, c1, c2, s
    cs := carry(0)
    c0 := carry(0)
    c1 := carry(0)
    c2 := carry(0)

    # create a string for subscripting. strings are immutable, new strings created
    s := "0000"
    # bit 0 is string position 4
    s[4+:1] := fulladder(a[4+:1], b[4+:1], cs, c0)
    s[3+:1] := fulladder(a[3+:1], b[3+:1], c0, c1)
    s[2+:1] := fulladder(a[2+:1], b[2+:1], c1, c2)
    s[1+:1] := fulladder(a[1+:1], b[1+:1], c2, cr)
    # cr.c is the overflow carry
    return s
end


<?php
$pid = pcntl_fork();
if ($pid == 0)
  echo "This is the new process\n";
else if ($pid > 0)
  echo "This is the original process\n";
else
  echo "ERROR: Something went wrong\n";
?>


(unless (fork)                         # In child process
   (println *Pid)                      # Print the child's PID
   (bye) )                             # and terminate


lvars ress;
if sys_fork(false) ->> ress then
   ;;; parent
   printf(ress, 'Child pid = %p\n');
else
   printf('In child\n');
endif;


import os

pid = os.fork()
if pid > 0:
 # parent code
else:
 # child code


p <- parallel::mcparallel({
        Sys.sleep(1)
        cat("\tChild pid: ", Sys.getpid(), "\n")
        TRUE
})
cat("Main pid: ", Sys.getpid(), "\n")
parallel::mccollect(p)

p <- parallel:::mcfork()
if (inherits(p, "masterProcess")) {
        Sys.sleep(1)
        cat("\tChild pid: ", Sys.getpid(), "\n")
        parallel:::mcexit(, TRUE)
}
cat("Main pid: ", Sys.getpid(), "\n")
unserialize(parallel:::readChildren(2))


and=: *.
or=: +.
not=: -.
xor=: (and not) or (and not)~
hadd=: and ,"0 xor
add=: ((({.,0:)@[ or {:@[ hadd {[email protected]]), }[email protected]])/@hadd


public class GateLogic
{
  // Basic gate interfaces
  public interface OneInputGate
  {  boolean eval(boolean input);  }

  public interface TwoInputGate
  {  boolean eval(boolean input1, boolean input2);  }

  public interface MultiGate
  {  boolean[] eval(boolean... inputs);  }

  // Create NOT
  public static OneInputGate NOT = new OneInputGate() {
    public boolean eval(boolean input)
    {  return !input;  }
  };

  // Create AND
  public static TwoInputGate AND = new TwoInputGate() {
    public boolean eval(boolean input1, boolean input2)
    {  return input1 && input2;  }
  };

  // Create OR
  public static TwoInputGate OR = new TwoInputGate() {
    public boolean eval(boolean input1, boolean input2)
    {  return input1 || input2;  }
  };

  // Create XOR
  public static TwoInputGate XOR = new TwoInputGate() {
    public boolean eval(boolean input1, boolean input2)
    {
      return OR.eval(
               AND.eval(input1, NOT.eval(input2)),
               AND.eval(NOT.eval(input1), input2)
             );
    }
  };

  // Create HALF_ADDER
  public static MultiGate HALF_ADDER = new MultiGate() {
    public boolean[] eval(boolean... inputs)
    {
      if (inputs.length != 2)
        throw new IllegalArgumentException();
      return new boolean[] {
        XOR.eval(inputs[0], inputs[1]),  // Output bit
        AND.eval(inputs[0], inputs[1])   // Carry bit
      };
    }
  };

  // Create FULL_ADDER
  public static MultiGate FULL_ADDER = new MultiGate() {
    public boolean[] eval(boolean... inputs)
    {
      if (inputs.length != 3)
        throw new IllegalArgumentException();
      // Inputs: CarryIn, A, B
      // Outputs: S, CarryOut
      boolean[] haOutputs1 = HALF_ADDER.eval(inputs[0], inputs[1]);
      boolean[] haOutputs2 = HALF_ADDER.eval(haOutputs1[0], inputs[2]);
      return new boolean[] {
        haOutputs2[0],                         // Output bit
        OR.eval(haOutputs1[1], haOutputs2[1])  // Carry bit
      };
    }
  };

  public static MultiGate buildAdder(final int numBits)
  {
    return new MultiGate() {
      public boolean[] eval(boolean... inputs)
      {
        // Inputs: A0, A1, A2..., B0, B1, B2...
        if (inputs.length != (numBits << 1))
          throw new IllegalArgumentException();
        boolean[] outputs = new boolean[numBits + 1];
        boolean[] faInputs = new boolean[3];
        boolean[] faOutputs = null;
        for (int i = 0; i < numBits; i++)
        {
          faInputs[0] = (faOutputs == null) ? false : faOutputs[1];  // CarryIn
          faInputs[1] = inputs[i];                                   // Ai
          faInputs[2] = inputs[numBits + i];                         // Bi
          faOutputs = FULL_ADDER.eval(faInputs);
          outputs[i] = faOutputs[0];                                 // Si
        }
        if (faOutputs != null)
          outputs[numBits] = faOutputs[1];                           // CarryOut
        return outputs;
      }
    };
  }

  public static void main(String[] args)
  {
    int numBits = Integer.parseInt(args[0]);
    int firstNum = Integer.parseInt(args[1]);
    int secondNum = Integer.parseInt(args[2]);
    int maxNum = 1 << numBits;
    if ((firstNum < 0) || (firstNum >= maxNum))
    {
      System.out.println("First number is out of range");
      return;
    }
    if ((secondNum < 0) || (secondNum >= maxNum))
    {
      System.out.println("Second number is out of range");
      return;
    }

    MultiGate multiBitAdder = buildAdder(numBits);
    // Convert input numbers into array of bits
    boolean[] inputs = new boolean[numBits << 1];
    String firstNumDisplay = "";
    String secondNumDisplay = "";
    for (int i = 0; i < numBits; i++)
    {
      boolean firstBit = ((firstNum >>> i) & 1) == 1;
      boolean secondBit = ((secondNum >>> i) & 1) == 1;
      inputs[i] = firstBit;
      inputs[numBits + i] = secondBit;
      firstNumDisplay = (firstBit ? "1" : "0") + firstNumDisplay;
      secondNumDisplay = (secondBit ? "1" : "0") + secondNumDisplay;
    }

    boolean[] outputs = multiBitAdder.eval(inputs);
    int outputNum = 0;
    String outputNumDisplay = "";
    String outputCarryDisplay = null;
    for (int i = numBits; i >= 0; i--)
    {
      outputNum = (outputNum << 1) | (outputs[i] ? 1 : 0);
      if (i == numBits)
        outputCarryDisplay = outputs[i] ? "1" : "0";
      else
        outputNumDisplay += (outputs[i] ? "1" : "0");
    }
    System.out.println("numBits=" + numBits);
    System.out.println("A=" + firstNumDisplay + " (" + firstNum + "), B=" + secondNumDisplay + " (" + secondNum + "), S=" + outputCarryDisplay + " " + outputNumDisplay + " (" + outputNum + ")");
    return;
  }

}


#lang racket
(define-values [P _out _in _err]
  (subprocess (current-output-port) (current-input-port) (current-error-port)
              (find-executable-path "du") "-hs" "/usr/share"))
;; wait for process to end, print messages as long as it runs
(let loop () (unless (sync/timeout 10 P) (printf "Still running...\n") (loop)))


use NativeCall;
sub fork() returns int32 is native { ... }

if fork() -> $pid {
    print "I am the proud parent of $pid.\n";
}
else {
    print "I am a child.  Have you seen my mommy?\n";
}


pid = fork
if pid
 # parent code
else
 # child code
end


run "someProgram.bas",#handle
render #handle     ' this runs the program until it waits
                   ' both the parent and child are running
' --------------------------------------------------------
' You can also call a function in the someProgram.bas program.
' For example if it had a DisplayBanner Funciton.
#handle DisplayBanner("Welcome!")


use nix::unistd::{fork, ForkResult};
use std::process::id;

fn main() {
    match fork() {
        Ok(ForkResult::Parent { child, .. }) => {
            println!(
                "This is the original process(pid: {}). New child has pid: {}",
                id(),
                child
            );
        }
        Ok(ForkResult::Child) => println!("This is the new process(pid: {}).", id()),
        Err(_) => println!("Something went wrong."),
    }
}


function acceptedBinFormat(bin) {
    if (bin == 1 || bin === 0 || bin === '0')
        return true;
    else
        return bin;
}

function arePseudoBin() {
    var args = [].slice.call(arguments), len = args.length;
    while(len--)
        if (acceptedBinFormat(args[len]) !== true)
            throw new Error('argument must be 0, \'0\', 1, or \'1\', argument ' + len + ' was ' + args[len]);
    return true;
}


import java.io.IOException

object Fork extends App {
  val builder: ProcessBuilder = new ProcessBuilder()
  val currentUser: String = builder.environment.get("USER")
  val command: java.util.List[String] = java.util.Arrays.asList("ps", "-f", "-U", currentUser)
  builder.command(command)
  try {
    val lines = scala.io.Source.fromInputStream(builder.start.getInputStream).getLines()
    println(s"Output of running $command is:")
    while (lines.hasNext) println(lines.next())
  }
  catch {
    case iox: IOException => iox.printStackTrace()
  }
}


var x = 42;
{ x += 1; say x }.fork.wait;     # x is 43 here
say x;                           # but here is still 42


[email protected](Process traits) forkAndDo: b
[| ret |
  (ret := lobby cloneSystem)
    first ifTrue: [p pipes addLast: ret second. ret second]
           ifFalse: [[p pipes clear. p pipes addLast: ret second. b applyWith: ret second] ensure: [lobby quit]]
].


'Here I am' displayNl.
|a|
a := [
  (Delay forSeconds: 2) wait .
  1 to: 100 do: [ :i | i displayNl ]
] fork.
'Child will start after 2 seconds' displayNl.
"wait to avoid terminating first the parent;
 a better way should use semaphores"
(Delay forSeconds: 10) wait.


case Posix.Process.fork () of
   SOME pid => print "This is the original process\n"
 | NONE     => print "This is the new process\n";


# Start with the 'not' and 'and' building blocks.
# These allow us to construct 'nand', 'or', and 'xor',
# and so on.

def bit_not: if . == 1 then 0 else 1 end;

def bit_and(a; b): if a == 1 and b == 1 then 1 else 0 end;

def bit_nand(a; b): bit_and(a; b) | bit_not;

def bit_or(a; b): bit_nand(bit_nand(a;a); bit_nand(b;b));

def bit_xor(a; b):
  bit_nand(bit_nand(bit_nand(a;b); a);
           bit_nand(bit_nand(a;b); b));

def halfAdder(a; b):
  { "carry": bit_and(a; b), "sum": bit_xor(a; b) };

def fullAdder(a; b; c):
  halfAdder(a; b) as $h0
  | halfAdder($h0.sum; c) as $h1
  | {"carry": bit_or($h0.carry; $h1.carry), "sum": $h1.sum };

# a and b should be strings of 0s and 1s, of length no greater than 4
def fourBitAdder(a; b):

  # pad on the left with 0s, and convert the string
  # representation ("101") to an array of integers ([1,0,1]).
  def pad: (4-length) * "0" + . | explode | map(. - 48);

  (a|pad) as $inA | (b|pad) as $inB
  | [][3] = null                                # an array for storing the four results
  | halfAdder($inA[3]; $inB[3]) as $pass
  | .[3] = $pass.sum                            # store the lsb
  | fullAdder($inA[2]; $inB[2]; $pass.carry) as $pass
  | .[2] = $pass.sum
  | fullAdder($inA[1]; $inB[1]; $pass.carry) as $pass
  | .[1] = $pass.sum
  | fullAdder($inA[0]; $inB[0]; $pass.carry) as $pass
  | .[0] = $pass.sum
  | map(tostring) | join("") ;


#!/usr/bin/env jsish
/* 4 bit adder simulation, in Jsish */
function not(a) { return a == 1 ? 0 : 1; }
function and(a, b) { return a + b < 2 ? 0 : 1; }
function nand(a, b) { return not(and(a, b)); }
function or(a, b) { return nand(nand(a,a), nand(b,b)); }
function xor(a, b) { return nand(nand(nand(a,b), a), nand(nand(a,b), b)); }

function halfAdder(a, b) { return { carry: and(a, b), sum: xor(a, b) }; }
function fullAdder(a, b, c) {
    var h0 = halfAdder(a, b),
        h1 = halfAdder(h0.sum, c);
    return {carry: or(h0.carry, h1.carry), sum: h1.sum };
}

function fourBitAdder(a, b) {
    // set to width 4, pad with 0 if too short and truncate right if too long
    var inA = Array(4),
        inB = Array(4),
        out = Array(4),
        i = 4,
        pass;

    if (a.length < 4) a = '0'.repeat(4 - a.length) + a;
    a = a.slice(-4);
    if (b.length < 4) b = '0'.repeat(4 - b.length) + b;
    b = b.slice(-4);
    while (i--) {
        var re = /0|1/;
        if (a[i] && !re.test(a[i])) throw('bad bit at a[' + i + '] of ' + quote(a[i]));
        if (b[i] && !re.test(b[i])) throw('bad bit at b[' + i + '] of ' + quote(b[i]));
        inA[i] = a[i] != 1 ? 0 : 1;
        inB[i] = b[i] != 1 ? 0 : 1;
    }

    printf('%s + %s = ', a, b);

    // now we can start adding... connecting the constructive blocks
    pass = halfAdder(inA[3], inB[3]);
    out[3] = pass.sum;
    pass = fullAdder(inA[2], inB[2], pass.carry);
    out[2] = pass.sum;
    pass = fullAdder(inA[1], inB[1], pass.carry);
    out[1] = pass.sum;
    pass = fullAdder(inA[0], inB[0], pass.carry);
    out[0] = pass.sum;

    var result = parseInt(pass.carry + out.join(''), 2);
    printf('%s  %d\n', out.join('') + ' carry ' + pass.carry, result);
    return result;
}

if (Interp.conf('unitTest')) {
    var bits = [['0000', '0000'], ['0000', '0001'], ['1000', '0001'],
                ['1010', '0101'], ['1000', '1000'], ['1100', '1100'],
                ['1111', '1111']];
    for (var pair of bits) {
        fourBitAdder(pair[0], pair[1]);
    }
;   fourBitAdder('1', '11');
;   fourBitAdder('10001', '01110');
;// fourBitAdder('0002', 'b');
}

/*
=!EXPECTSTART!=
0000 + 0000 = 0000 carry 0  0
0000 + 0001 = 0001 carry 0  1
1000 + 0001 = 1001 carry 0  9
1010 + 0101 = 1111 carry 0  15
1000 + 1000 = 0000 carry 1  16
1100 + 1100 = 1000 carry 1  24
1111 + 1111 = 1110 carry 1  30
fourBitAdder('1', '11') ==> 0001 + 0011 = 0100 carry 0  4
4
fourBitAdder('10001', '01110') ==> 0001 + 1110 = 1111 carry 0  15
15
fourBitAdder('0002', 'b') ==>
PASS!: err = bad bit at a[3] of "2"
=!EXPECTEND!=
*/


| parent
 ssx 'R child'
 wait 'childevent'
 'child is running...' []
 'child will end...' []
 post 'dieevent'
 delay 5000


package require Expect
# or
package require Tclx

for {set i 0} {$i < 100} {incr i} {
    set pid [fork]
    switch $pid {
        -1 {
            puts "Fork attempt #$i failed."
        }
        0 {
            puts "I am child process #$i."
            exit
        }
        default {
            puts "The parent just spawned child process #$i."
        }
    }
}


needs shell
getpid is-data PID
[ fork getpid PID = [ ." Child PID: " . cr ] [ ." In child\n" ] ifTrueFalse ] invoke


i=0
(while test $i -lt 10; do
  sleep 1
  echo "Child process"
  i=`expr $i + 1`
done) &
while test $i -lt 5; do
  sleep 2
  echo "Parent process"
  i=`expr $i + 1`
done


(echo "Process 1" >&2 ;sleep 5; echo "1 done" ) | (echo "Process 2";cat;echo "2 done")


using Printf

xor{T<:Bool}(a::T, b::T) = (a&~b)|(~a&b)

halfadder{T<:Bool}(a::T, b::T) = (xor(a,b), a&b)

function fulladder{T<:Bool}(a::T, b::T, c::T=false)
    (s, ca) = halfadder(c, a)
    (s, cb) = halfadder(s, b)
    (s, ca|cb)
end

function adder(a::BitArray{1}, b::BitArray{1}, c0::Bool=false)
    len = length(a)
    length(b) == len || error("Addend width mismatch.")
    c = c0
    s = falses(len)
    for i in 1:len
        (s[i], c) = fulladder(a[i], b[i], c)
    end
    (s, c)
end

function adder{T<:Integer}(m::T, n::T, wid::T=4, c0::Bool=false)
    a = bitpack(digits(m, 2, wid))[1:wid]
    b = bitpack(digits(n, 2, wid))[1:wid]
    adder(a, b, c0)
end

Base.bits(n::BitArray{1}) = join(reverse(int(n)), "")


// version 1.1.51

val Boolean.I get() = if (this) 1 else 0

val Int.B get() = this != 0

class Nybble(val n3: Boolean, val n2: Boolean, val n1: Boolean, val n0: Boolean) {
    fun toInt() = n0.I + n1.I * 2 + n2.I * 4 + n3.I * 8

    override fun toString() = "${n3.I}${n2.I}${n1.I}${n0.I}"
}

fun Int.toNybble(): Nybble {
    val n = BooleanArray(4)
    for (k in 0..3) n[k] = ((this shr k) and 1).B
    return Nybble(n[3], n[2], n[1], n[0])
}

fun xorGate(a: Boolean, b: Boolean) = (a && !b) || (!a && b)

fun halfAdder(a: Boolean, b: Boolean) = Pair(xorGate(a, b), a && b)

fun fullAdder(a: Boolean, b: Boolean, c: Boolean): Pair<Boolean, Boolean> {
    val (s1, c1) = halfAdder(c, a)
    val (s2, c2) = halfAdder(s1, b)
    return s2 to (c1 || c2)
}

fun fourBitAdder(a: Nybble, b: Nybble): Pair<Nybble, Int> {
    val (s0, c0) = fullAdder(a.n0, b.n0, false)
    val (s1, c1) = fullAdder(a.n1, b.n1, c0)
    val (s2, c2) = fullAdder(a.n2, b.n2, c1)
    val (s3, c3) = fullAdder(a.n3, b.n3, c2)
    return Nybble(s3, s2, s1, s0) to c3.I
}

const val f = "%s + %s = %d %s (%2d + %2d = %2d)"

fun test(i: Int, j: Int) {
    val a = i.toNybble()
    val b = j.toNybble()
    val (r, c) = fourBitAdder(a, b)
    val s = c * 16 + r.toInt()
    println(f.format(a, b, c, r, i, j, s))
}

fun main(args: Array<String>) {
    println(" A      B     C  R     I    J    S")
    for (i in 0..15) {
        for (j in i..minOf(i + 1, 15)) test(i, j)
    }
}


Module Module1

    Sub Fork()
        Console.WriteLine("Spawned Thread")
    End Sub

    Sub Main()
        Dim t As New System.Threading.Thread(New Threading.ThreadStart(AddressOf Fork))
        t.Start()

        Console.WriteLine("Main Thread")
        t.Join()
    End Sub

End Module


do (fork sleep.1
         prn.1)
   prn.2


/* fork.wren */

class C {
    foreign static fork()

    foreign static usleep(usec)

    foreign static wait()
}

var pid = C.fork()
if (pid == 0) {
    C.usleep(10000)
    System.print("\tchild process: done")
} else if (pid < 0) {
    System.print("fork error")
} else {
    System.print("waiting for child %(pid)...")
    System.print("child %(C.wait()) finished")
}


option casemap:none

windows64     equ 1
linux64       equ 3

ifndef __THREAD_CLASS__
__THREAD_CLASS__      equ 1

  if @Platform eq windows64
    option dllimport:<kernel32>
      CreateThread    proto :qword, :qword, :qword, :qword, :dword, :qword
      HeapAlloc       proto :qword, :dword, :qword
      HeapFree        proto :qword, :dword, :qword
      ExitProcess     proto :dword
      GetProcessHeap  proto
    option dllimport:<none>
      exit            equ ExitProcess
  elseif @Platform eq linux64
    pthread_create    proto :qword, :qword, :qword, :qword
    malloc            proto :qword
    free              proto :qword
    exit              proto :dword
  endif

  printf              proto :qword, :vararg

  CLASS thread
    CMETHOD createthread
  ENDMETHODS
    tid     dq ?
    hThread dq ?
  ENDCLASS

  METHOD thread, Init, <VOIDARG>, <>
    mov rax, thisPtr
    ret
  ENDMETHOD

  METHOD thread, createthread, <VOIDARG>, <>, lpCode:qword, arg:qword
    local z:qword,x:qword

    mov rbx, thisPtr
    assume rbx:ptr thread
    mov z, lpCode
    mov x, 0
    .if arg != 0
      mov x, arg
    .endif
    if @Platform eq windows64
      invoke CreateThread, 0, 0, z, x, 0, addr [rbx].tid
      .if rax == 0
        mov rax, -1
        ret
      .endif
    elseif @Platform eq linux64
      invoke pthread_create, addr [rbx].tid, 0, z, x
      .if rax != 0
        mov rax, -1
        ret
      .endif
    endif
    mov [rbx].hThread, rax
    assume rbx:nothing
    ret
  ENDMETHOD

  METHOD thread, Destroy, <VOIDARG>, <>
    ;; We should close all thread handles here..
    ;; But I don't care. In this example, exit does it for me. :]
    ret
  ENDMETHOD

endif               ;;__THREAD_CLASS__

thChild             proto

.data

.code
main proc
  local pThread:ptr thread

  mov pThread, _NEW(thread)
  invoke printf, CSTR("--> Main thread spwaning child thread...",10)
  lea rax, thChild
  pThread->createthread(rax, 0)
  _DELETE(pThread)
  ;; Just a loop so Exit doesn't foobar the program.
  ;; No reason to include and call Sleep just for this.. -.-
  mov rcx, 20000
  @@:
    add rax, 1
  loop @B
  invoke exit, 0
  ret
main endp

thChild proc
  invoke printf, CSTR("--> Goodbye, World! from a child.... thread.",10)
  mov rax, 0
  ret
thChild endp
end


{def xor
 {lambda {:a :b}
  {or {and :a {not :b}} {and :b {not :a}}}}}
-> xor

{def halfAdder
 {lambda {:a :b}
  {cons {and :a :b} {xor :a :b}}}}
-> halfAdder

{def fullAdder
 {lambda {:a :b :c}
  {let {  {:b :b}
          {:ha1 {halfAdder :c :a}} }
   {let { {:ha1 :ha1}
          {:ha2 {halfAdder {cdr :ha1} :b}} }
        {cons {or {car :ha1} {car :ha2}} {cdr :ha2}} }}}}
-> fullAdder

{def 4bitsAdder
 {lambda {:a4 :a3 :a2 :a1 :b4 :b3 :b2 :b1}
  {let { {:a4 :a4} {:a3 :a3} {:a2 :a2} {:b4 :b4} {:b3 :b3} {:b2 :b2}
         {:fa1 {fullAdder :a1 :b1 false}} }
   {let { {:a4 :a4} {:a3 :a3} {:b4 :b4} {:b3 :b3}
          {:fa1 :fa1}
          {:fa2 {fullAdder :a2 :b2 {car :fa1}}} }
    {let { {:a4 :a4} {:b4 :b4}
           {:fa1 :fa1} {:fa2 :fa2}
           {:fa3 {fullAdder :a3 :b3 {car :fa2}}} }
     {let { {:fa1 :fa1} {:fa2 :fa2} {:fa3 :fa3}
            {:fa4 {fullAdder :a4 :b4 {car :fa3}}} }
      {car :fa4} {cdr :fa4} {cdr :fa3} {cdr :fa2} {cdr :fa1}}}}}}}
-> 4bitsAdder

{def bin2bool
 {lambda {:b}
  {if {W.empty? {W.rest :b}}
   then {= {W.first :b} 1}
   else {= {W.first :b} 1} {bin2bool {W.rest :b}}}}}
-> bin2bool

{def bool2bin
 {lambda {:b}
  {if {S.empty? {S.rest :b}}
   then {if {S.first :b} then 1 else 0}
   else {if {S.first :b} then 1 else 0}{bool2bin {S.rest :b}}}}}
-> bool2bin

{def bin2dec
 {def bin2dec.r
  {lambda {:p :r}
   {if {A.empty? :p}
    then :r
    else {bin2dec.r {A.rest :p} {+ {A.first :p} {* 2 :r}}}}}}
 {lambda {:p} {bin2dec.r {A.split :p} 0}}}
-> bin2dec

{def add
 {def numbers 0000 0001 0010 0011 0100 0101 0110 0111
              1000 1001 1010 1011 1100 1101 1110 1111}
 {lambda {:a :b}
  {bin2dec
   {bool2bin
    {4bitsAdder {bin2bool {S.get :a {numbers}}}
                {bin2bool {S.get :b {numbers}}}}}}}}
-> add

{table
 {S.map {lambda {:i} {tr
  {S.map {{lambda {:i :j} {td {add :i :j}}} :i}
  {S.serie 0 15}}}}
 {S.serie 0 15}}
}
->
 0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15
 1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16
 2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17
 3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18
 4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19
 5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20
 6   7   8   9  10  11  12  13  14  15  16  17  18  19  20  21
 7   8   9  10  11  12  13  14  15  16  17  18  19  20  21  22
 8   9  10  11  12  13  14  15  16  17  18  19  20  21  22  23
 9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24
10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25
11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26
12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27
13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28
14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29
15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30


int Key, Process;
[Key:= SharedMem(4);    \allocate 4 bytes of memory common to both processes
Process:= Fork(1);      \start one child process
case Process of
  0:  [Lock(Key);  Text(0, "Rosetta");  CrLf(0);  Unlock(Key)]; \parent process
  1:  [Lock(Key);  Text(0, "Code");     CrLf(0);  Unlock(Key)]  \child process
other [Lock(Key);  Text(0, "Error");    CrLf(0);  Unlock(Key)];
Join(Process);          \wait for child process to finish
]


-- Build XOR from AND, OR and NOT
function xor (a, b) return (a and not b) or (b and not a) end

-- Can make half adder now XOR exists
function halfAdder (a, b) return xor(a, b), a and b end

-- Full adder is two half adders with carry outputs OR'd
function fullAdder (a, b, cIn)
    local ha0s, ha0c = halfAdder(cIn, a)
    local ha1s, ha1c = halfAdder(ha0s, b)
    local cOut, s = ha0c or ha1c, ha1s
    return cOut, s
end

-- Carry bits 'ripple' through adders, first returned value is overflow
function fourBitAdder (a3, a2, a1, a0, b3, b2, b1, b0) -- LSB-first
    local fa0c, fa0s = fullAdder(a0, b0, false)
    local fa1c, fa1s = fullAdder(a1, b1, fa0c)
    local fa2c, fa2s = fullAdder(a2, b2, fa1c)
    local fa3c, fa3s = fullAdder(a3, b3, fa2c)
    return fa3c, fa3s, fa2s, fa1s, fa0s -- Return as MSB-first
end

-- Take string of noughts and ones, convert to native boolean type
function toBool (bitString)
    local boolList, bit = {}
    for digit = 1, 4 do
        bit = string.sub(string.format("%04d", bitString), digit, digit)
        if bit == "0" then table.insert(boolList, false) end
        if bit == "1" then table.insert(boolList, true) end
    end
    return boolList
end

-- Take list of booleans, convert to string of binary digits (variadic)
function toBits (...)
    local bStr = ""
    for i, bool in pairs{...} do
        if bool then bStr = bStr .. "1" else bStr = bStr .. "0" end
    end
    return bStr
end

-- Little driver function to neaten use of the adder
function add (n1, n2)
    local A, B = toBool(n1), toBool(n2)
    local v, s0, s1, s2, s3 = fourBitAdder( A[1], A[2], A[3], A[4],
                                            B[1], B[2], B[3], B[4] )
    return toBits(s0, s1, s2, s3), v
end

-- Main procedure (usage examples)
print("SUM", "OVERFLOW\n")
print(add(0001, 0001)) -- 1 + 1 = 2
print(add(0101, 1010)) -- 5 + 10 = 15
print(add(0000, 1111)) -- 0 + 15 = 15
print(add(0001, 1111)) -- 1 + 15 = 16 (causes overflow)


Module  FourBitAdder {
	Flush
	dim not(0 to 1),and(0 to 1, 0 to 1),or(0 to 1, 0 to 1)
	not(0)=1,0
	and(0,0)=0,0,0,1
	or(0,0)=0,1,1,1
	xor=lambda not(),and(),or() (a,b)-> or(and(a, not(b)), and(b, not(a)))
	ha=lambda xor, and() (a,b, &s, &c)->{
		s=xor(a,b)
		c=and(a,b)
	}
	fa=lambda ha, or() (a, b, c0, &s, &c1)->{
		def sa,ca,cb
		call ha(a, c0, &sa, &ca)
		call ha(sa, b, &s,&cb)
		c1=or(ca,cb)
	}
	add4=lambda fa (inpA(), inpB(), &v, &out()) ->{
		dim carry(0 to 4)=0
		carry(0)=v    \\ 0 or 1  borrow
		for i=0 to 3
			\\ mm=fa(InpA(i), inpB(i), carry(i), &out(i), &carry(i+1)) ' same as this
			Call fa(InpA(i), inpB(i), carry(i), &out(i), &carry(i+1))
		next
		v=carry(4)
	}
	dim res(0 to 3)=-1,  low()
	source=lambda->{
		shift 1, -stack.size  ' reverse stack items
		=array([])  ' convert current stack to array, empty current stack
	}
	def v, k, k_low
	Print "First Example 4-bit"
	Print "A", "", 1, 0, 1, 0
	Print "B", "", 1, 0, 0, 1
	call add4(source(1,0,1,0), source(1,0,0,1), &v, &res())
	k=each(res() end to start)  ' k is an iterator, now configure to read items in reverse
	Print "A+B",v, k    ' print 1 0 0 1 1
	Print "Second Example 4-bit"
	v-=v
	Print "A", "", 0, 1, 1, 0
	Print "B", "", 0, 1, 1, 1
	call add4(source(0,1,1,0), source(0,1,1,1), &v, &res())
	k=each(res() end to start)  ' k is an iterator, now configure to read items in reverse
	Print "A+B",v, k    ' print  0 1 1 0 1
	Print "Third Example 8-bit"
	v-=v
	Print "A ", "", 1, 0, 0, 0, 0, 1, 1, 0
	Print "B ", "", 1, 1, 1, 1, 1, 1, 1, 1
	call add4(source(0,1,1,0), source(1,1,1,1), &v, &res())
	low()=res()  ' a copy of res()
	' v passed to second adder
	dim res(0 to 3)=-1
	call add4(source(1,0,0,0), source(1,1,1,1), &v, &res())
	k_low=each(low() end to start)  ' k_low is an iterator, now configure to read items in reverse
	k=each(res() end to start)  ' k is an iterator, now configure to read items in reverse
	Print "A+B",v, k, k_low   ' print  1 1 0 0 0 0 1 0 1
}
FourBitAdder


function [S,v] = fourBitAdder(input1,input2)

    %Make sure that only 4-Bit numbers are being added. This assumes that
    %if input1 and input2 are a vector of multiple decimal numbers, then
    %the binary form of these vectors are an n by 4 matrix.
    assert((size(input1,2) == 4) && (size(input2,2) == 4),'This will only work on 4-Bit Numbers');

    %Converts MATLAB binary strings to matricies of 1 and 0
    function mat = binStr2Mat(binStr)
        mat = zeros(size(binStr));
        for i = (1:numel(binStr))
            mat(i) = str2double(binStr(i));
        end
    end

    %XOR decleration
    function AxorB = xor(A,B)
        AxorB = or(and(A,not(B)),and(B,not(A)));
    end

    %Half-Adder decleration
    function [S,C] = halfAdder(A,B)
        S = xor(A,B);
        C = and(A,B);
    end

    %Full-Adder decleration
    function [S,Co] = fullAdder(A,B,Ci)
       [SAdder1,CAdder1] = halfAdder(Ci,A);
       [S,CAdder2] = halfAdder(SAdder1,B);
       Co = or(CAdder1,CAdder2);
    end

    %The rest of this code is the 4-bit adder

    binStrFlag = false; %A flag to determine if the original input was a binary string

    %If either of the inputs was a binary string, convert it to a matrix of
    %1's and 0's.
    if ischar(input1)
       input1 = binStr2Mat(input1);
       binStrFlag = true;
    end
    if ischar(input2)
       input2 = binStr2Mat(input2);
       binStrFlag = true;
    end

    %This does the addition
    S = zeros(size(input1));

    [S(:,4),Co] = fullAdder(input1(:,4),input2(:,4),0);
    [S(:,3),Co] = fullAdder(input1(:,3),input2(:,3),Co);
    [S(:,2),Co] = fullAdder(input1(:,2),input2(:,2),Co);
    [S(:,1),v] = fullAdder(input1(:,1),input2(:,1),Co);

    %If the original inputs were binary strings, convert the output of the
    %4-bit adder to a binary string with the same formatting as the
    %original binary strings.
    if binStrFlag
        S = num2str(S);
        v = num2str(v);
    end
end %fourBitAdder


XOR(Y,Z) ;Uses logicals - i.e., 0 is false, anything else is true (1 is used if setting a value)
 QUIT (Y&'Z)!('Y&Z)
HALF(W,X)
 QUIT $$XOR(W,X)_"^"_(W&X)
FULL(U,V,CF)
 NEW F1,F2
 S F1=$$HALF(U,V)
 S F2=$$HALF($P(F1,"^",1),CF)
 QUIT $P(F2,"^",1)_"^"_($P(F1,"^",2)!($P(F2,"^",2)))
FOUR(Y,Z,C4)
 NEW S,I,T
 FOR I=4:-1:1 SET T=$$FULL($E(Y,I),$E(Z,I),C4),$E(S,I)=$P(T,"^",1),C4=$P(T,"^",2)
 K I,T
 QUIT S_"^"_C4


"""
To run:
    python3 Four_bit_adder_011.py
"""

from myhdl import *

#     define set of primitives

@block
def NOTgate( a,  q ):   # define component name & interface
   """ q <- not(a) """
   @always_comb   # define asynchronous logic
   def NOTgateLogic():
      q.next = not a

   return NOTgateLogic   # return defined logic function, named 'NOTgate'

@block
def ANDgate( a, b,  q ):
   """ q <- a and b """
   @always_comb
   def ANDgateLogic():
      q.next = a and b

   return ANDgateLogic

@block
def ORgate( a, b,  q ):
   """ q <- a or b """
   @always_comb
   def ORgateLogic():
      q.next = a or b

   return ORgateLogic

#     build components using defined primitive set

@block
def XORgate( a, b,  q ):
   """ q <- a xor b """
   # define internal signals
   nota, notb, annotb, bnnota = [Signal(bool(0)) for i in range(4)]
   # name sub-components, and their interconnect
   inv0 = NOTgate( a,  nota )
   inv1 = NOTgate( b,  notb )
   and2a = ANDgate( a, notb,  annotb )
   and2b = ANDgate( b, nota,  bnnota )
   or2a = ORgate( annotb, bnnota,  q )

   return inv0, inv1, and2a, and2b, or2a

@block
def HalfAdder( in_a, in_b,  summ, carry ):
   """ carry,sum is the sum of in_a, in_b """
   and2a =  ANDgate(in_a, in_b,  carry)
   xor2a =  XORgate(in_a, in_b,  summ)

   return and2a, xor2a

@block
def FullAdder( fa_c0, fa_a, fa_b,  fa_s, fa_c1 ):
   """ fa_c1,fa_s is the sum of fa_c0, fa_a, fa_b """

   ha1_s, ha1_c1, ha2_c1 = [Signal(bool(0)) for i in range(3)]

   HalfAdder01 = HalfAdder( fa_c0, fa_a,  ha1_s, ha1_c1 )
   HalfAdder02 = HalfAdder( ha1_s, fa_b,  fa_s,  ha2_c1 )
   or2a = ORgate(ha1_c1, ha2_c1,  fa_c1)

   return HalfAdder01, HalfAdder02, or2a

@block
def Adder4b( ina, inb,  cOut, sum4):
   ''' assemble 4 full adders '''

   cl = [Signal(bool()) for i in range(0,4)]  # carry signal list
   sl = [Signal(bool()) for i in range(4)]  # sum signal list

   HalfAdder0 = HalfAdder(        ina(0), inb(0),  sl[0], cl[1] )
   FullAdder1 = FullAdder( cl[1], ina(1), inb(1),  sl[1], cl[2] )
   FullAdder2 = FullAdder( cl[2], ina(2), inb(2),  sl[2], cl[3] )
   FullAdder3 = FullAdder( cl[3], ina(3), inb(3),  sl[3], cOut )

   sc = ConcatSignal(*reversed(sl))  # create internal bus for output list

   @always_comb
   def list2intbv():
      sum4.next = sc  # assign internal bus to actual output

   return HalfAdder0, FullAdder1, FullAdder2, FullAdder3, list2intbv

"""   define signals and code for testing
      -----------------------------------   """
t_co, t_s, t_a, t_b, dbug =  [Signal(bool(0)) for i in range(5)]
ina4, inb4, sum4 =  [Signal(intbv(0)[4:])  for i in range(3)]

from random import randrange

@block
def Test_Adder4b():
   ''' Test Bench for Adder4b '''
   dut = Adder4b( ina4, inb4,  t_co, sum4 )

   @instance
   def check():
      print( "\n      b   a   |  c1    s   \n     -------------------" )
      for i in range(15):
         ina4.next, inb4.next = randrange(2**4), randrange(2**4)
         yield delay(5)
         print( "     %2d  %2d   |  %2d   %2d     " \
                % (ina4,inb4, t_co,sum4) )
         assert t_co * 16 + sum4 == ina4 + inb4  # test result
      print()

   return dut, check

"""   instantiate components and run test
      -----------------------------------   """

def main():
   simInst = Test_Adder4b()
   simInst.name = "mySimInst"
   simInst.config_sim(trace=True)  # waveform trace turned on
   simInst.run_sim(duration=None)

   inst = Adder4b( ina4, inb4,  t_co, sum4 )  #Multibit_Adder( a, b, s)
   inst.convert(hdl='VHDL')  # export VHDL
   inst.convert(hdl='Verilog')  # export Verilog

if __name__ == '__main__':
   main()