/*REXX pgm converts a # to English into the phrase:  a is b, b is c, ... four is magic. */
numeric digits 3003                              /*be able to handle gihugic numbers.   */
parse arg x                                      /*obtain optional numbers from the C.L.*/
if x=''  then x= -164 0 4 6 11 13 75 100 337 9223372036854775807   /*use these defaults?*/
@.= .                                            /*stemmed array used for memoization.  */
       do j=1  for words(x)                      /*process each of the numbers in list. */
       say 4_is( word(x, j) )                    /*display phrase that'll be returned.  */
       say                                       /*display a blank line between outputs.*/
       end   /*j*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
4_is:  procedure expose @.;     parse arg #,,$                /*obtain the start number.*/
       if #\==4  then do  until L==4                          /*Not 4?   Process number.*/
                      @.#= $spell#(#  'quiet minus negative') /*spell number in English.*/
                      #= @.#;           L= length(#)          /*get the length of spelt#*/
                      if @.L==.  then @.L= $spell#(L 'quiet') /*¬spelt before? Spell it.*/
                      $= $   #   "is"   @.L','                /*add phrase to the answer*/
                      #= L                                    /*use the new number, ··· */
                      end   /*until*/                         /* ··· which will be spelt*/
       $= strip($ 'four is magic.')              /*finish the sentence with the finale. */
       parse var $ first 2 other;  upper first   /*capitalize the first letter of output*/
       return first  ||  other                   /*return the sentence to the invoker.  */


width: 1000
height: 1000

trunkLength: 400
scaleFactor: 0.6
startingAngle: 1.5 * pi
deltaAngle: 0.2 * pi

drawTree: function [out x y len theta][
    if len < 1 -> return null

    x2: x + len * cos theta
    y2: y + len * sin theta

    'out ++ ~"<line x1='|x|' y1='|y|' x2='|x2|' y2='|y2|' style='stroke: white; stroke-width:1'/>\n"

    drawTree out x2 y2 len*scaleFactor theta+deltaAngle
    drawTree out x2 y2 len*scaleFactor theta-deltaAngle
]

svg: {
    <?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'>
        <rect width="100%" height="100%" fill="black"/>
}

drawTree svg 0.5*width height trunkLength startingAngle
'svg ++ "</svg>"

write "fractal.svg" svg


#SingleInstance, Force
#NoEnv
SetBatchLines, -1

; Uncomment if Gdip.ahk is not in your standard library
; #Include, Gdip.ahk

FileOut		:= A_Desktop "\MyNewFile.png"
TreeColor	:= 0xff0066ff	; ARGB
TrunkWidth 	:= 10		; Pixels
TrunkLength	:= 80		; Pixels
Angle 		:= 60		; Degrees
ImageWidth 	:= 670		; Pixels
ImageHeight 	:= 450		; Pixels
Branches	:= 13
Decrease	:= 0.81

Angle := (Angle * 0.01745329252) / 2
	, Points := {}
	, Points[1, "Angle"] := 0
	, Points[1, "X"] := ImageWidth // 2
	, Points[1, "Y"] := ImageHeight - TrunkLength

if (!pToken := Gdip_Startup()) {
	MsgBox, 48, Gdiplus error!, Gdiplus failed to start. Please ensure you have Gdiplus on your system.
	ExitApp
}
OnExit, Exit

pBitmap := Gdip_CreateBitmap(ImageWidth, ImageHeight)
	, G := Gdip_GraphicsFromImage(pBitmap)
	, Gdip_SetSmoothingMode(G, 4)
	, pBrush := Gdip_BrushCreateSolid(0xff000000)
	, Gdip_FillRectangle(G, pBrush, -5, -5, ImageWidth + 10, ImageHeight + 10)
	, Gdip_DeleteBrush(pBrush)
	, pPen := Gdip_CreatePen(TreeColor, TrunkWidth/Decrease)
	, Gdip_DrawLine(G, pPen, Points.1.X, Points.1.Y, Points.1.X, ImageHeight)
	, Gdip_DeletePen(pPen)

Loop, % Branches {
	NewPoints := {}
	pPen := Gdip_CreatePen(TreeColor, TrunkWidth)
	for Each, Point in Points {
		N1 := A_Index * 2
			, N2 := (A_Index * 2) + 1
			, NewPoints[N1, "X"] := Point.X + (TrunkLength * Sin(NewPoints[N1, "Angle"] := Point.Angle - Angle))
			, NewPoints[N1, "Y"] := Point.Y - (TrunkLength * Cos(NewPoints[N1].Angle))
			, NewPoints[N2, "X"] := Point.X + (TrunkLength * Sin(NewPoints[N2, "Angle"] := Point.Angle + Angle))
			, NewPoints[N2, "Y"] := Point.Y - (TrunkLength * Cos(NewPoints[N2].Angle))
			, Gdip_DrawLine(G, pPen, Point.X, Point.Y, NewPoints[N1].X, NewPoints[N1].Y)
			, Gdip_DrawLine(G, pPen, Point.X, Point.Y, NewPoints[N2].X, NewPoints[N2].Y)
	}
	TrunkWidth *= Decrease
		, TrunkLength *= Decrease
		, Points := NewPoints
		, Gdip_DeletePen(pPen)
}

Gdip_SaveBitmapToFile(pBitmap, FileOut)
	, Gdip_DisposeImage(pBitmap)
	, Gdip_DeleteGraphics(G)
Run, % FileOut

Exit:
Gdip_Shutdown(pToken)
ExitApp


/*  Checking numbers from 0 to 10 */
for c = 0 to 10
	See checkmagic(c) + NL
next

/* The functions */

Func CheckMagic numb
	CardinalN = ""
	Result = ""
	if isnumber(numb) = false or numb < 0 or numb > 999_999_999_999_999
		Return "ERROR: Number entered is incorrect"
	ok
	if numb = 4
		Result = "Four is magic."
	else
		While True
			if CardinalN = "four"
				Result += "four is magic"
				exit
			ok
			strnumb = StringNumber(numb)
			CardinalN = StringNumber(len(strnumb))
			Result += strnumb + " is " + CardinalN + ", "
			numb = len(strnumb)
		End
		Result += "."
		Result = upper(Result[1]) + Right(Result, len(Result) -1)
	ok

	Return  Result

Func StringNumber cnumb

	NumStr = [:n0 = "zero", :n1 = "one", :n2 = "two", :n3 = "three", :n4 = "four", :n5 = "five",
		:n6 = "six", :n7 = "seven", :n8 = "eight", :n9 = "nine", :n10 = "ten",
		:n11 = "eleven", :n12 = "twelve", :n13 = "thirteen", :n14 = "fourteen", :n15 = "fifteen",
		:n16 = "sixteen", :n17 = "seventeen", :n18 = "eighteen", :n19 = "nineteen",
		:n20 = "twenty", :n30 = "thirty", :n40 = "fourty", :n50 = "fifty", :n60 = "sixty", :n70 = "seventy", :n80 = "eighty", :n90 = "ninety"]

	numLev = [:l1 = "", :l2 = "thousand", :l3 = "million", :l4 = "billion", :l5 = "trillion"]

	Result = ""

	if cnumb > 0
		decimals(0)
		snumb = string((cnumb))
		lnumb = [""]
		fl = floor(len(snumb) / 3)
		if fl > 0
			for i = 1 to  fl
				lnumb[i] = right(snumb, 3)
				snumb = left(snumb, len(snumb) -3)
				lnumb + ""
			next
			if (len(snumb) % 3) > 0
				lnumb[len(lnumb)] = snumb
			else
				del(lnumb, len(lnumb))
			ok
		else
			lnumb[1] = snumb
		ok
		for l = len(lnumb) to 1 step -1
			bnumb = lnumb[l]
			bResult = ""
			if number(bnumb) != 0
				for n = len(bnumb) to 1 step -1
					if (len(bnumb) = 3 and n = 2) or (len(bnumb) = 2 and n = 1)
						if number(bnumb[n]) > 1
							eval("bResult = NumStr[:n" + bnumb[n] + "0] + ' ' + bResult")
						elseif number(bnumb[n]) = 1
							eval("bResult = NumStr[:n" + bnumb[n] + bnumb[n+1] + "] + ' ' + bResult")
						ok
					else
						if len(bnumb) = 3 and n = 1 and number(bnumb[1]) > 0
							if trim(bResult) != ""
								bResult = " " + bResult
							ok
							if number(bnumb[1]) > 1
								bResult = "hundreds" + bResult
							else
								bResult = "hundred" + bResult
							ok
							if left(trim(bResult), 7) = "hundred"
								bResult = bResult + " "
							ok
						ok
						if (len(bnumb) = 3 and n = 1 and number(bnumb[1]) = 0) OR (len(bnumb) = n and number(bnumb[n]) = 0) OR (len(bnumb) = 3 and number(bnumb[2]) = 1) OR (len(bnumb) = 2 and number(bnumb[1]) = 1)
							loop
						ok
						eval("bResult = NumStr[:n" + bnumb[n] + "] + ' ' + bResult")
					ok
				next
				Result = Result + bResult
				if  l > 1
					if number(bnumb) > 1
						eval("Result = Result + numLev[:l" + l + "] + 's ' ")
					else
						eval("Result = Result + numLev[:l" + l + "] + ' ' ")
					ok
				ok
			ok
		next
	else
		Result = Result + NumStr[:n0]
	ok

Return trim(Result)


module NumberToWord

  NUMBERS = {  # taken from https://en.wikipedia.org/wiki/Names_of_large_numbers#cite_ref-a_14-3
    1 => 'one',
    2 => 'two',
    3 => 'three',
    4 => 'four',
    5 => 'five',
    6 => 'six',
    7 => 'seven',
    8 => 'eight',
    9 => 'nine',
    10 => 'ten',
    11 => 'eleven',
    12 => 'twelve',
    13 => 'thirteen',
    14 => 'fourteen',
    15 => 'fifteen',
    16 => 'sixteen',
    17 => 'seventeen',
    18 => 'eighteen',
    19 => 'nineteen',
    20 => 'twenty',
    30 => 'thirty',
    40 => 'forty',
    50 => 'fifty',
    60 => 'sixty',
    70 => 'seventy',
    80 => 'eighty',
    90 => 'ninety',
    100 => 'hundred',
    1000 => 'thousand',
    10 ** 6 => 'million',
    10 ** 9 => 'billion',
    10 ** 12 => 'trillion',
    10 ** 15 => 'quadrillion',
    10 ** 18 => 'quintillion',
    10 ** 21 => 'sextillion',
    10 ** 24 => 'septillion',
    10 ** 27 => 'octillion',
    10 ** 30 => 'nonillion',
    10 ** 33 => 'decillion'}.reverse_each.to_h

  refine Integer do
    def to_english
      return 'zero' if i.zero?
      words =  self < 0 ? ['negative'] : []
      i = self.abs
      NUMBERS.each do |k, v|
        if k <= i then
          times = i/k
          words << times.to_english if k >= 100
          words << v
          i -= times * k
        end
        return words.join(" ") if i.zero?
      end
    end
  end

end

using  NumberToWord

def magic4(n)
  words = []
  until n == 4
    s = n.to_english
    n = s.size
    words << "#{s} is #{n.to_english}"
  end
  words << "four is magic."
  words.join(", ").capitalize
end

[0, 4, 6, 11, 13, 75, 337, -164, 9_876_543_209].each{|n| puts magic4(n) }


let rec forward_difference = function
    a :: (b :: _ as xs) ->
      b - a :: forward_difference xs
  | _ ->
      []

let rec nth_forward_difference n xs =
  if n = 0 then
    xs
  else
    nth_forward_difference (pred n) (forward_difference xs)


: forwardDiff(l)     l right(l size 1 -) l zipWith(#-) ;
: forwardDiffN(n, l)  l #[ forwardDiff dup println ] times(n) ;


graphsize 300,300

level = 12 : len =63		# initial values
x = 230: y = 285
rotation = pi/2

A1 = pi/27 : A2 = pi/8		# constants which determine shape
C1 = 0.7 : C2 = 0.85

dim xs(level+1) : dim ys(level+1)	# stacks

fastgraphics
color black
rect 0,0,graphwidth,graphheight
refresh
color green
gosub tree
refresh
imgsave "Fractal_tree_BASIC-256.png", "PNG"
end

tree:
	xs[level] = x : ys[level] = y
	gosub putline
	if level>0 then
		level = level - 1
		len = len*C1
		rotation = rotation - A1
		gosub tree
		len = len/C1*C2
		rotation = rotation + A1 + A2
		gosub tree
		rotation = rotation - A2
		len = len/C2
		level = level + 1
	end if
	x = xs[level] : y = ys[level]
	return

putline:
	yn = -sin(rotation)*len + y
	xn = cos(rotation)*len + x
	line x,y,xn,yn
	x = xn : y = yn
	return


#include <SDL/SDL.h>
#ifdef WITH_CAIRO
#include <cairo.h>
#else
#include <SDL/sge.h>
#endif
#include <cairo.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>

#ifdef WITH_CAIRO
#define PI 3.1415926535
#endif

#define SIZE           800   // determines size of window
#define SCALE          5     // determines how quickly branches shrink (higher value means faster shrinking)
#define BRANCHES       14    // number of branches
#define ROTATION_SCALE 0.75  // determines how slowly the angle between branches shrinks (higher value means slower shrinking)
#define INITIAL_LENGTH 50    // length of first branch

double rand_fl(){
  return (double)rand() / (double)RAND_MAX;
}

void draw_tree(SDL_Surface * surface, double offsetx, double offsety,
               double directionx, double directiony, double size,
               double rotation, int depth) {
#ifdef WITH_CAIRO
  cairo_surface_t *surf = cairo_image_surface_create_for_data( surface->pixels,
                                                               CAIRO_FORMAT_RGB24,
							       surface->w, surface->h,
							       surface->pitch );
  cairo_t *ct = cairo_create(surf);

  cairo_set_line_width(ct, 1);
  cairo_set_source_rgba(ct, 0,0,0,1);
  cairo_move_to(ct, (int)offsetx, (int)offsety);
  cairo_line_to(ct, (int)(offsetx + directionx * size), (int)(offsety + directiony * size));
  cairo_stroke(ct);
#else
  sge_AALine(surface,
      (int)offsetx, (int)offsety,
      (int)(offsetx + directionx * size), (int)(offsety + directiony * size),
      SDL_MapRGB(surface->format, 0, 0, 0));
#endif
  if (depth > 0){
    // draw left branch
    draw_tree(surface,
        offsetx + directionx * size,
        offsety + directiony * size,
        directionx * cos(rotation) + directiony * sin(rotation),
        directionx * -sin(rotation) + directiony * cos(rotation),
        size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE,
        rotation * ROTATION_SCALE,
        depth - 1);

    // draw right branch
    draw_tree(surface,
        offsetx + directionx * size,
        offsety + directiony * size,
        directionx * cos(-rotation) + directiony * sin(-rotation),
        directionx * -sin(-rotation) + directiony * cos(-rotation),
        size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE,
        rotation * ROTATION_SCALE,
        depth - 1);
  }
}

void render(SDL_Surface * surface){
  SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 255, 255, 255));
  draw_tree(surface,
      surface->w / 2.0,
      surface->h - 10.0,
      0.0, -1.0,
      INITIAL_LENGTH,
      PI / 8,
      BRANCHES);
  SDL_UpdateRect(surface, 0, 0, 0, 0);
}

int main(){
  SDL_Surface * screen;
  SDL_Event evt;

  SDL_Init(SDL_INIT_VIDEO);

  srand((unsigned)time(NULL));

  screen = SDL_SetVideoMode(SIZE, SIZE, 32, SDL_HWSURFACE);

  render(screen);
  while(1){
    if (SDL_PollEvent(&evt)){
      if(evt.type == SDL_QUIT) break;
    }
    SDL_Delay(1);
  }
  SDL_Quit();
  return 0;
}


fn main() {
    magic(4);
    magic(2_340);
    magic(765_000);
    magic(27_000_001);
    magic(999_123_090);
    magic(239_579_832_723_441);
    magic(std::u64::MAX);
}

fn magic(num: u64) {
    if num == 4 {
        println!("four is magic!");
        println!();
        return;
    }
    let name = number_name(num);
    let len = name.len() as u64;
    print!("{} is {}, ", name, number_name(len));
    magic(len);
}

const LOW: &'static [&'static str] = &[
    "zero", "one", "two", "three", "four", "five",
    "six", "seven", "eight","nine", "ten",
    "eleven", "twelve", "thirteen", "fourteen", "fifteen",
    "sixteen", "seventeen", "eighteen", "nineteen"
];
const MED: &'static [&'static str] = &[
    "twenty", "thirty", "forty", "fifty",
    "sixy", "seventy", "eighty", "ninety"
];
const HIGH: &'static [&'static str] = &[
    "thousand", "million", "billion",
    "trillion", "quadrillion", "quintillion"
];

fn number_name(num: u64) -> String {
    if num < 20 {
        return LOW[num as usize].to_string();
    }
    if num < 100 {
        let index = ((num / 10) - 2) as usize;
        let tens = MED[index].to_string();
        let remainder = num % 10;
        if remainder > 0 {
            return format!("{}-{}", tens, number_name(remainder));
        }
        return tens;
    }
    if num < 1000 {
        let hundreds = LOW[(num / 100) as usize];
        let remainder = num % 100;
        if remainder > 0 {
            return format!("{} hundred {}", hundreds, number_name(remainder));
        }
        return format!("{} hundred", hundreds);
    }

    let mut remainder = num % 1000;
    let mut cur = if remainder > 0 { number_name(remainder) } else { "".to_string() };
    let mut n = num / 1000;

    for noun in HIGH.iter() {
        if n > 0 {
            remainder = n % 1000;
            if remainder > 0 {
                // this condition resolves double space issues
                cur =
                    if cur.len() > 0 { format!("{} {} {}", number_name(remainder), noun, cur ) }
                    else { format!("{} {}", number_name(remainder), noun) }
            }
            n /= 1000;
        }
    }
    return cur;
}


func cardinal(n) {
    static lingua_en = frequire("Lingua::EN::Numbers")
    lingua_en.num2en(n) - / and|,/g
}

func four_is_magic(n) {
    var str = ""
    loop {
       str += (cardinal(n) + " is ")
       if (n == 4) {
           str += "magic."
           break
       } else {
           n = cardinal(n).len
           str += (cardinal(n) + ", ")
       }
   }
   str.tc
}

[0, 4, 6, 11, 13, 75, 337, -164, 9_876_543_209].each { |n|
    say four_is_magic(n)
}


import Foundation

func fourIsMagic(_ number: NSNumber) -> String {
    let formatter = NumberFormatter()
    formatter.numberStyle = .spellOut
    formatter.locale = Locale(identifier: "en_EN")

    var result: [String] = []

    var numberString = formatter.string(from: number)!
    result.append(numberString.capitalized)

    while numberString != "four" {
        numberString = formatter.string(from: NSNumber(value: numberString.count))!
        result.append(contentsOf: [" is ", numberString, ", ", numberString])
    }

    result.append(" is magic.")
    return result.joined()
}

for testInput in [23, 1000000000, 20140, 100, 130, 151, -7] {
    print(fourIsMagic(testInput as NSNumber))
}


Program ForwardDifferenceDemo(output);

procedure fowardDifference(list: array of integer);
  var
    b: array of integer;
    i, newlength: integer;
  begin
    newlength := length(list) - 1;
    if newlength > 0 then
    begin
      setlength(b, newlength);
      for i := low(b) to high(b) do
      begin
        b[i] := list[i+1] - list[i];
        write (b[i]:6);
      end;
      writeln;
      fowardDifference(b);
    end;
  end;

var
  a: array [1..10] of integer = (90, 47, 58, 29, 22, 32, 55, 5, 55, 73);
begin
  fowardDifference(a);
end.


#include <windows.h>
#include <string>
#include <math.h>

//--------------------------------------------------------------------------------------------------
using namespace std;

//--------------------------------------------------------------------------------------------------
const float PI = 3.1415926536f;

//--------------------------------------------------------------------------------------------------
class myBitmap
{
public:
    myBitmap() : pen( NULL ) {}
    ~myBitmap()
    {
	DeleteObject( pen );
	DeleteDC( hdc );
	DeleteObject( bmp );
    }

    bool create( int w, int h )
    {
	BITMAPINFO	bi;
	void		*pBits;
	ZeroMemory( &bi, sizeof( bi ) );
	bi.bmiHeader.biSize	   = sizeof( bi.bmiHeader );
	bi.bmiHeader.biBitCount	   = sizeof( DWORD ) * 8;
	bi.bmiHeader.biCompression = BI_RGB;
	bi.bmiHeader.biPlanes	   = 1;
	bi.bmiHeader.biWidth	   =  w;
	bi.bmiHeader.biHeight	   = -h;

	HDC dc = GetDC( GetConsoleWindow() );
	bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
	if( !bmp ) return false;

	hdc = CreateCompatibleDC( dc );
	SelectObject( hdc, bmp );
	ReleaseDC( GetConsoleWindow(), dc );

	width = w; height = h;

	return true;
    }

    void setPenColor( DWORD clr )
    {
	if( pen ) DeleteObject( pen );
	pen = CreatePen( PS_SOLID, 1, clr );
	SelectObject( hdc, pen );
    }

    void saveBitmap( string path )
    {
	BITMAPFILEHEADER	fileheader;
	BITMAPINFO			infoheader;
	BITMAP				bitmap;
	DWORD*				dwpBits;
	DWORD				wb;
	HANDLE				file;

	GetObject( bmp, sizeof( bitmap ), &bitmap );

	dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
	ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
	ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
	ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );

	infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
	infoheader.bmiHeader.biCompression = BI_RGB;
	infoheader.bmiHeader.biPlanes = 1;
	infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
	infoheader.bmiHeader.biHeight = bitmap.bmHeight;
	infoheader.bmiHeader.biWidth = bitmap.bmWidth;
	infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );

	fileheader.bfType    = 0x4D42;
	fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
	fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;

	GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );

	file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
	WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
	WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
	WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
	CloseHandle( file );

	delete [] dwpBits;
    }

    HDC getDC()     { return hdc; }
    int getWidth()  { return width; }
    int getHeight() { return height; }

private:
    HBITMAP bmp;
    HDC	    hdc;
    HPEN    pen;
    int     width, height;
};
//--------------------------------------------------------------------------------------------------
class vector2
{
public:
    vector2() { x = y = 0; }
    vector2( int a, int b ) { x = a; y = b; }
    void set( int a, int b ) { x = a; y = b; }
    void rotate( float angle_r )
    {
	float _x = static_cast<float>( x ),
	      _y = static_cast<float>( y ),
	       s = sinf( angle_r ),
	       c = cosf( angle_r ),
	       a = _x * c - _y * s,
	       b = _x * s + _y * c;

	x = static_cast<int>( a );
	y = static_cast<int>( b );
    }

    int x, y;
};
//--------------------------------------------------------------------------------------------------
class fractalTree
{
public:
    fractalTree()		      { _ang = DegToRadian( 24.0f ); }
    float DegToRadian( float degree ) { return degree * ( PI / 180.0f ); }

    void create( myBitmap* bmp )
    {
	_bmp = bmp;
	float line_len = 130.0f;

	vector2 sp( _bmp->getWidth() / 2, _bmp->getHeight() - 1 );
	MoveToEx( _bmp->getDC(), sp.x, sp.y, NULL );
	sp.y -= static_cast<int>( line_len );
	LineTo( _bmp->getDC(), sp.x, sp.y);

	drawRL( &sp, line_len, 0, true );
	drawRL( &sp, line_len, 0, false );
    }

private:
    void drawRL( vector2* sp, float line_len, float a, bool rg )
    {
	line_len *= .75f;
	if( line_len < 2.0f ) return;

	MoveToEx( _bmp->getDC(), sp->x, sp->y, NULL );
	vector2 r( 0, static_cast<int>( line_len ) );

        if( rg ) a -= _ang;
        else a += _ang;

	r.rotate( a );
	r.x += sp->x; r.y = sp->y - r.y;

	LineTo( _bmp->getDC(), r.x, r.y );

	drawRL( &r, line_len, a, true );
	drawRL( &r, line_len, a, false );
    }

    myBitmap* _bmp;
    float     _ang;
};
//--------------------------------------------------------------------------------------------------
int main( int argc, char* argv[] )
{
    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );

    myBitmap bmp;
    bmp.create( 640, 512 );
    bmp.setPenColor( RGB( 255, 255, 0 ) );

    fractalTree tree;
    tree.create( &bmp );

    BitBlt( GetDC( GetConsoleWindow() ), 0, 20, 648, 512, bmp.getDC(), 0, 0, SRCCOPY );

    bmp.saveBitmap( "f://rc//fracTree.bmp" );

    system( "pause" );

    return 0;
}
//--------------------------------------------------------------------------------------------------


#!/usr/bin/env bash
name_of() {
  # return the English name for a numeric value
  local -i n=$1

  if (( n < 0 )); then
    printf 'negative %s\n' "$(name_of $(( -n )))"
    return 0
  fi

  # Names for numbers that fit in a bash integer
  local -A names=([0]=zero [1]=one [2]=two [3]=three [4]=four [5]=five
                  [6]=six [7]=seven [8]=eight [9]=nine [10]=ten [11]=eleven
                  [12]=twelve [13]=thirteen [14]=fourteen [15]=fifteen
                  [16]=sixteen [17]=seventeen [18]=eighteen [19]=nineteen
                  [20]=twenty [30]=thirty [40]=forty [50]=fifty [60]=sixty
                  [70]=seventy [80]=eighty [90]=ninety [100]=hundred
                  [1000]=thousand [1000000]=million [1000000000]=billion
                  [1000000000000]=trillion [1000000000000000]=quadrillion
                  [1000000000000000000]=quintillion)

  # The powers of 10 above 10, in descending order
  local powers_of_10=($(printf '%s\n' "${!names[@]}" | sort -nr | grep '00$'))

  # find the largest power of 10 that is smaller than n
  local -i i=0
  local -i p=${powers_of_10[i]}
  while ((  p > n  && i < ${#powers_of_10[@]}-1 )); do
    i=i+1
    p=${powers_of_10[$i]}
  done

  # if we found one, split on it and construct quotient 'name' remainder
  if (( n >= p )); then
    local -i quotient=n/p
    local -i remainder=n%p
    local remname=
    if (( remainder > 0 )); then
        remname=$(name_of $remainder)
    fi
    printf '%s %s\n' "$(name_of $quotient)" "${names[$p]}${remname:+ $remname}"
  elif (( n > 20 )); then
    # things are a little different under 100, since the multiples of
    # 10 have their own names
    local -i remainder=n%10
    local -i tens=n-remainder
    local remname=
    if (( remainder > 0 )); then
      remname=-$(name_of $remainder)
    fi
    printf '%s\n' "${names[$tens]}${remname:+$remname}"
  else
    printf '%s\n' "${names[$n]}"
  fi

  return 0
}

# Convert numbers into the length of their names
# Display the series of values in name form until
# the length turns into four; then terminate with "four is magic."
# Again, takes a second argument, this time a prefix, to
# facilitate tail recursion.
four_is_magic() {
  local -i n=$1
  local prefix=$2
  local name=$(name_of $n)

  # capitalize the first entry
  if [[ -z $prefix ]]; then
    name=${name^}
  fi

  # Stop at 4, otherwise count the length of the name and recurse
  if (( $n == 4 )); then
     printf '%s%s is magic.\n' "${prefix:+$prefix, }" "$name"
  else
     local -i len=${#name}
     four_is_magic "$len" "${prefix:+$prefix, }$name is $(name_of $len)"
  fi
}


import math
fn main() {
	for n in [i64(0), 4, 6, 11, 13, 75, 100, 337, -164,
		math.max_i64,
     ] {
		println(four_is_magic(n))
	}
}

fn four_is_magic(nn i64) string {
    mut n := nn
	mut s := say(n)
	s = s[..1].to_upper() + s[1..]
	mut t := s
	for n != 4 {
		n = i64(s.len)
		s = say(n)
		t += " is " + s + ", " + s
	}
	t += " is magic."
	return t
}

const small = ["zero", "one", "two", "three", "four", "five", "six",
	"seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen",
	"fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
const tens = ["", "", "twenty", "thirty", "forty",
	"fifty", "sixty", "seventy", "eighty", "ninety"]
const illions = ["", " thousand", " million", " billion",
	" trillion", " quadrillion", " quintillion"]

fn say(nn i64) string {
	mut t := ''
    mut n := nn
	if n < 0 {
		t = "negative "
		// Note, for math.MinInt64 this leaves n negative.
		n = -n
	}
	match true {
	    n < 20 {
            t += small[n]
        }
        n < 100 {
            t += tens[n/10]
            s := n % 10
            if s > 0 {
                t += "-" + small[s]
            }
        }
        n < 1000 {
            t += small[n/100] + " hundred"
            s := n % 100
            if s > 0 {
                t += " " + say(s)
            }
        }
        else {
            // work right-to-left
            mut sx := ""
            for i := 0; n > 0; i++ {
                p := n % 1000
                n /= 1000
                if p > 0 {
                    mut ix := say(p) + illions[i]
                    if sx != "" {
                        ix += " " + sx
                    }
                    sx = ix
                }
            }
		    t += sx
        }
	}
	return t
}


import "/str" for Str

var small = ["zero", "one", "two", "three", "four", "five", "six",  "seven", "eight", "nine", "ten", "eleven",
             "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]

var tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]

var illions = ["", " thousand", " million", " billion"," trillion", " quadrillion", " quintillion"]

var say
say = Fn.new { |n|
    var t = ""
    if (n < 0) {
        t = "negative "
        n = -n
    }
    if (n < 20) {
        t = t + small[n]
    } else if (n < 100) {
        t = t + tens[(n/10).floor]
        var s = n % 10
        if (s > 0) t = t + "-" + small[s]
    } else if (n < 1000) {
        t = t + small[(n/100).floor] + " hundred"
        var s = n % 100
        System.write("") // guards against VM recursion bug
        if (s > 0) t = t + " " + say.call(s)
    } else {
        var sx = ""
        var i = 0
        while (n > 0) {
            var p = n % 1000
            n = (n/1000).floor
            if (p > 0) {
                System.write("") // guards against VM recursion bug
                var ix = say.call(p) + illions[i]
                if (sx != "") ix = ix + " " + sx
                sx = ix
            }
            i = i + 1
        }
        t = t + sx
    }
    return t
}

var fourIsMagic = Fn.new { |n|
    var s = Str.capitalize(say.call(n))
    var t = s
    while (n != 4) {
        n = s.count
        s = say.call(n)
        t = t + " is " + s + ", " + s
    }
    return t + " is magic."
}

for (n in [0, 4, 6, 11, 13, 75, 100, 337, -164,  9007199254740991]) {
    System.print(fourIsMagic.call(n))
}


with javascript_semantics
function fwd_diff_n(sequence s, integer order)
    assert(order<length(s))
    s = deep_copy(s)
    for i=1 to order do
        for j=1 to length(s)-1 do
            s[j] = s[j+1]-s[j]
        end for
        s = s[1..-2]
    end for
    return s
end function

constant s = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73}
for i=1 to 9 do
    ?fwd_diff_n(s,i)
end for


<?php

function forwardDiff($anArray, $times = 1) {
  if ($times <= 0) { return $anArray; }
  for ($accumilation = array(), $i = 1, $j = count($anArray); $i < $j; ++$i) {
    $accumilation[] = $anArray[$i] - $anArray[$i - 1];
  }
  if ($times === 1) { return $accumilation; }
  return forwardDiff($accumilation, $times - 1);
}

class ForwardDiffExample extends PweExample {

  function _should_run_empty_array_for_single_elem() {
    $expected = array($this->rand()->int());
    $this->spec(forwardDiff($expected))->shouldEqual(array());
  }

  function _should_give_diff_of_two_elem_as_single_elem() {
    $twoNums = array($this->rand()->int(), $this->rand()->int());
    $expected = array($twoNums[1] - $twoNums[0]);
    $this->spec(forwardDiff($twoNums))->shouldEqual($expected);
  }

  function _should_compute_correct_forward_diff_for_longer_arrays() {
    $diffInput = array(10, 2, 9, 6, 5);
    $expected  = array(-8, 7, -3, -1);
    $this->spec(forwardDiff($diffInput))->shouldEqual($expected);
  }

  function _should_apply_more_than_once_if_specified() {
    $diffInput = array(4, 6, 9, 3, 4);
    $expectedAfter1 = array(2, 3, -6, 1);
    $expectedAfter2 = array(1, -9, 7);
    $this->spec(forwardDiff($diffInput, 1))->shouldEqual($expectedAfter1);
    $this->spec(forwardDiff($diffInput, 2))->shouldEqual($expectedAfter2);
  }

  function _should_return_array_unaltered_if_no_times() {
    $this->spec(forwardDiff($expected = array(1,2,3), 0))->shouldEqual($expected);
  }

}


import javax.swing {

	JFrame { exitOnClose }
}
import java.awt {

	Color { white, black },
	Graphics
}
import ceylon.numeric.float {

	cos,
	toRadians,
	sin
}

shared void run() {

    value fractalTree = object extends JFrame("fractal tree") {

        background = black;
        setBounds(100, 100, 800, 600);
        resizable = false;
        defaultCloseOperation = exitOnClose;

        shared actual void paint(Graphics g) {

            void drawTree(Integer x1, Integer y1, Float angle, Integer depth) {
                if (depth <= 0) {
                    return;
                }
                value x2 = x1 + (cos(toRadians(angle)) * depth * 10.0).integer;
                value y2 = y1 + (sin(toRadians(angle)) * depth * 10.0).integer;
                g.drawLine(x1, y1, x2, y2);
                drawTree(x2, y2, angle - 20, depth - 1);
                drawTree(x2, y2, angle + 20, depth - 1);
            }

            g.color = white;
            drawTree(400, 500, -90.0, 9);
        }
    };

    fractalTree.visible = true;
}


(import '[java.awt Color Graphics]
	'javax.swing.JFrame)

(defn deg-to-radian [deg] (* deg Math/PI 1/180))
(defn cos-deg [angle] (Math/cos (deg-to-radian angle)))
(defn sin-deg [angle] (Math/sin (deg-to-radian angle)))

(defn draw-tree [^Graphics g, x y angle depth]
  (when (pos? depth)
    (let [x2 (+ x (int (* depth 10 (cos-deg angle))))
	  y2 (+ y (int (* depth 10 (sin-deg angle))))]
      (.drawLine g x y x2 y2)
      (draw-tree g x2 y2 (- angle 20) (dec depth))
      (recur     g x2 y2 (+ angle 20) (dec depth)))))

(defn fractal-tree [depth]
  (doto (proxy [JFrame] []
	  (paint [g]
		 (.setColor g Color/BLACK)
		 (draw-tree g 400 500 -90 depth)))
    (.setBounds 100 100 800 600)
    (.setResizable false)
    (.setDefaultCloseOperation JFrame/DISPOSE_ON_CLOSE)
    (.show)))

(fractal-tree 9)


fcn fourIsMagic(int){
   if(int==0) return("Zero is four, four is magic.");
   string:="";
   while(1){ c:=nth(int,False);
      string+="%s is ".fmt(c);
      if(int = ( if(int==4) 0 else c.len() )){
	 string+="%s, ".fmt(nth(int,False));
      }else{
         string+="magic.";
	 break;
      }
   }
   string[0].toUpper() + string[1,*]
}


go =>
   L = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73],
   foreach(I in 1..L.length-1)
      println([d=I,diffi(L,I)])
   end,
   nl,
   % All differences (a sublist to save space)
   println(alldiffs(L[1..6])),
   nl.

% Difference of the list
diff(L) = Diff =>
   Diff = [L[I]-L[I-1] : I in 2..L.length].

% The i'th list difference
diffi(L,D) = Diff =>
   Diff1 = L,
   foreach(_I in 1..D)
      Diff1 := diff(Diff1)
   end,
   Diff = Diff1.

% all differences
alldiffs(L) = Diffs =>
   Diffs1 = [],
   Diff = L,
   foreach(_I in 1..L.length-1)
      Diff := diff(Diff),
      Diffs1 := Diffs1 ++ [Diff]
   end,
   Diffs = Diffs1.


(de fdiff (Lst)
   (mapcar - (cdr Lst) Lst) )

(for (L (90 47 58 29 22 32 55 5 55 73) L (fdiff L))
   (println L) )


/* Forward differences. */ /* 23 April 2010 */
differences: procedure options (main);
   declare a(10) fixed(10) static initial
      (7, 3, 9, 250, 300, 4, 68, 72, 154, 601);
   declare (i, j, m, n, t, u) fixed binary;

   m = hbound(a,1);
   get (n); if n > m then signal error;
   put skip edit (a) (F(7));
   do i = 1 to n;
      t = a(i);
      do j = i+1 to m;
         u = a(j);
         a(j) = a(j) - t;
         t = u;
      end;
      put skip edit (a) (F(7));
   end;
   put skip edit ((a(i) do i = n+1 to m)) (F(9));

end differences;


To add a fraction to some fraction things:
Allocate memory for a fraction thing.
Put the fraction into the fraction thing's fraction.
Append the fraction thing to the fraction things.

To create some fraction things:
Add 90-1/2 to the fraction things.
Add 47/1 to the fraction things.
Add 58/1 to the fraction things.
Add 29/1 to the fraction things.
Add 22/1 to the fraction things.
Add 32/1 to the fraction things.
Add 55/1 to the fraction things.
Add 5/1 to the fraction things.
Add 55/1 to the fraction things.
Add 73-1/2 to the fraction things.

To find the difference of some fraction things:
If the fraction things' count is less than 2, exit.
Get a fraction thing from the fraction things.
Loop.
If the fraction thing's next is nil, remove the fraction thing from the fraction things; destroy the fraction thing; exit.
Put the fraction thing's next's fraction minus the fraction thing's fraction into the fraction thing's fraction.
Put the fraction thing's next into the fraction thing.
Repeat.

To find the difference of some fraction things given an order:
If a counter is past the order, exit.
Find the difference of the fraction things.
Repeat.

A fraction thing is a thing with a fraction.

An order is a number.

To run:
Start up.
Create some fraction things.
Write "Original list:" on the console.
Show the fraction things.
Find the difference of the fraction things given 4.
Write "Order 4 forward difference:" on the console.
Show the fraction things.
Destroy the fraction things.
Wait for the escape key.
Shut down.

To show some fraction things:
Get a fraction thing from the fraction things.
Loop.
If the fraction thing is nil, write "" on the console; exit.
Write "" then the fraction thing's fraction on the console without advancing.
If the fraction thing's next is not nil, write ", " on the console without advancing.
Put the fraction thing's next into the fraction thing.
Repeat.


;; (require :lispbuilder-sdl)

(defun deg-to-radian (deg)
  "converts degrees to radians"
  (* deg pi 1/180))

(defun cos-deg (angle)
  "returns cosin of the angle expressed in degress"
  (cos (deg-to-radian angle)))

(defun sin-deg (angle)
  "returns sin of the angle expressed in degress"
  (sin (deg-to-radian angle)))

(defun draw-tree (surface x y angle depth)
  "draws a branch of the tree on the sdl-surface"
  (when (plusp depth)
    (let ((x2 (+ x (round (* depth 10 (cos-deg angle)))))
	  (y2 (+ y (round (* depth 10 (sin-deg angle))))))
      (sdl:draw-line-* x y x2 y2 :surface surface :color sdl:*green*)
      (draw-tree surface x2 y2 (- angle 20) (1- depth))
      (draw-tree surface x2 y2 (+ angle 20) (1- depth)))))

(defun fractal-tree (depth)
  "shows a window with a fractal tree"
  (sdl:with-init ()
    (sdl:window 800 600 :title-caption "fractal-tree")
    (sdl:clear-display sdl:*black*)
    (draw-tree sdl:*default-surface* 400 500 -90 depth)
    (sdl:update-display)
    (sdl:with-events ()
      (:video-expose-event ()
			   (sdl:update-display))
      (:quit-event ()
		   t))))

(fractal-tree 9)


define forward_difference(l);
    lvars res = [], prev, el;
    if l = [] then
        return([]);
    endif;
    front(l) -> prev;
    for el in back(l) do
        cons(el - prev, res) -> res;
        el -> prev;
    endfor;
    rev(res);
enddefine;

define nth_difference(l, n);
    lvars res = l, i;
    for i from 1 to n do
        forward_difference(res) -> res;
    endfor;
    res;
enddefine;


Procedure forward_difference(List a())
  If ListSize(a()) <= 1
    ClearList(a()): ProcedureReturn
  EndIf
  Protected NewList b()
  CopyList(a(), b())
  LastElement(a()): DeleteElement(a())
  SelectElement(b(), 1)
  ForEach a()
    a() - b(): NextElement(b())
  Next
EndProcedure

Procedure nth_difference(List a(), List b(), n)
  Protected i
  CopyList(a(), b())
  For i = 1 To n
    forward_difference(b())
  Next
EndProcedure

Procedure.s display(List a())
  Protected output.s
  ForEach a()
    output + Str(a()) + ","
  Next
  ProcedureReturn RTrim(output,",")
EndProcedure

DataSection
  ;list data
  Data.i 10 ;element count
  Data.i 90, 47, 58, 29, 22, 32, 55, 5, 55, 73
EndDataSection

;create and fill list
Define i
NewList a()
Read.i i
While i > 0
  AddElement(a()): Read.i a(): i - 1
Wend

If OpenConsole()
  NewList b()
  For i = 1 To 10
    nth_difference(a(), b(), i)
    PrintN(Str(i) + "   [" + display(b()) + "]")
  Next

  Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
  CloseConsole()
EndIf


import std.stdio, std.math;

enum width = 1000, height = 1000; // Image dimension.
enum length = 400;                // Trunk size.
enum scale = 6.0 / 10;            // Branch scale relative to trunk.

void tree(in double x, in double y, in double length, in double angle) {
    if (length < 1)
        return;
    immutable x2 = x + length * angle.cos;
    immutable y2 = y + length * angle.sin;
    writefln("<line x1='%f' y1='%f' x2='%f' y2='%f' " ~
             "style='stroke:black;stroke-width:1'/>", x, y, x2, y2);
    tree(x2, y2, length * scale, angle + PI / 5);
    tree(x2, y2, length * scale, angle - PI / 5);
}

void main() {
    "<svg width='100%' height='100%' version='1.1'
     xmlns='http://www.w3.org/2000/svg'>".writeln;
    tree(width / 2.0, height, length, 3 * PI / 2);
    "</svg>".writeln;
}


func tree x y deg n . .
  if n > 0
    linewidth n * 0.4
    move x y
    x += cos deg * n * 1.3 * (randomf + 0.5)
    y += sin deg * n * 1.3 * (randomf + 0.5)
    line x y
    call tree x y deg - 20 n - 1
    call tree x y deg + 20 n - 1
  .
.
timer 0
on timer
  clear
  call tree 50 90 -90 10
  timer 1
.


let (cos, sin, pi) = System.Math.Cos, System.Math.Sin, System.Math.PI

let (width, height) = 1000., 1000. // image dimension
let scale = 6./10.                 // branch scale relative to trunk
let length = 400.                  // trunk size

let rec tree x y length angle =
    if length >= 1. then
        let (x2, y2) = x + length * (cos angle),  y + length * (sin angle)
        printfn "<line x1='%f' y1='%f' x2='%f' y2='%f' style='stroke:rgb(0,0,0);stroke-width:1'/>"
            x y x2 y2
        tree x2 y2 (length*scale) (angle + pi/5.)
        tree x2 y2 (length*scale) (angle - pi/5.)

printfn "<?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.)
printfn "</svg>"


using fwt
using gfx

class FractalCanvas : Canvas
{
  new make () : super() {}

  Void drawTree (Graphics g, Int x1, Int y1, Int angle, Int depth)
  {
    if (depth == 0) return
    Int x2 := x1 + (angle.toFloat.toRadians.cos * depth * 10.0).toInt;
    Int y2 := y1 + (angle.toFloat.toRadians.sin * depth * 10.0).toInt;
    g.drawLine(x1, y1, x2, y2);
    drawTree(g, x2, y2, angle - 20, depth - 1);
    drawTree(g, x2, y2, angle + 20, depth - 1);
  }

  override Void onPaint (Graphics g)
  {
    drawTree (g, 400, 500, -90, 9)
  }
}

class FractalTree
{
  public static Void main ()
  {
    Window
    {
      title = "Fractal Tree"
      size = Size(800, 600)
      FractalCanvas(),
    }.open
  }
}


  [ times
      [ [] swap behead
        swap witheach
          [ tuck dip [ - join ] ]
        drop ] ]                  is f-diff ( [ n --> [ )

  ' [ 90 47 58 29 22 32 55 5 55 73 ]

  dup size times
    [ dup i^
      dup echo say ": "
      f-diff echo cr ]
  drop


forwarddif <- function(a, n) {
  if ( n == 1 )
    a[2:length(a)] - a[1:length(a)-1]
  else {
    r <- forwarddif(a, 1)
    forwarddif(r, n-1)
  }
}

fdiff <- function(a, n) {
  r <- a
  for(i in 1:n) {
    r <- r[2:length(r)] - r[1:length(r)-1]
  }
  r
}

v <- c(90, 47, 58, 29, 22, 32, 55, 5, 55, 73)

print(forwarddif(v, 9))
print(fdiff(v, 9))


#lang racket

(define (forward-difference list)
  (for/list ([x (cdr list)] [y list]) (- x y)))

(define (nth-forward-difference n list)
  (for/fold ([list list]) ([n n]) (forward-difference list)))

(nth-forward-difference 9 '(90 47 58 29 22 32 55 5 55 73))
;; -> '(-2921)


sub dif(@array [$, *@tail]) { @tail Z- @array }
sub difn($array, $n) { ($array, &dif ... *)[$n] }


' version 17-03-2017
' compile with: fbc -s gui

Const As Double deg2rad = Atn(1) / 45
Dim Shared As Double scale = 0.76
Dim Shared As Double spread = 25 * deg2rad ' convert degree's to rad's

Sub branch(x1 As ULong, y1 As ULong, size As ULong, angle As Double, depth As ULong)

    Dim As ULong x2, y2

    x2 = x1 + size * Cos(angle)
    y2 = y1 + size * Sin(angle)

    Line (x1,y1) - (x2,y2), 2  ' palette color green
    If depth > 0 Then
        branch(x2, y2, size * scale, angle - spread, depth -1)
        branch(x2, y2, size * scale, angle + spread, depth -1)
    End If

End Sub

' ------=< MAIN >=-----

Dim As Double angle = -90 * deg2rad ' make sure that the tree grows up
Dim As ULong  SizeX = 800
Dim As ULong  SizeY = SizeX * 3 \ 4
Dim As Double  size = SizeY \ 4
Dim As ULong  depth = 11

ScreenRes SizeX, SizeY, 8
WindowTitle ("Fractal Tree")

branch(SizeX\2, SizeY, size, angle, depth)

' empty keyboard buffer
While InKey <> "" : Wend
windowtitle ("Fractal Tree, hit any key to end program")
Sleep
End


module FractalTree where

import Java.IO
import Prelude.Math

data AffineTransform = native java.awt.geom.AffineTransform where
  native new :: () -> STMutable s AffineTransform
  native clone :: Mutable s AffineTransform -> STMutable s AffineTransform
  native rotate :: Mutable s AffineTransform -> Double -> ST s ()
  native scale :: Mutable s AffineTransform -> Double -> Double -> ST s ()
  native translate :: Mutable s AffineTransform -> Double -> Double -> ST s ()

data BufferedImage = native java.awt.image.BufferedImage where
  pure native type_3byte_bgr "java.awt.image.BufferedImage.TYPE_3BYTE_BGR" :: Int
  native new :: Int -> Int -> Int -> STMutable s BufferedImage
  native createGraphics :: Mutable s BufferedImage -> STMutable s Graphics2D

data Color = pure native java.awt.Color where
  pure native black "java.awt.Color.black" :: Color
  pure native green "java.awt.Color.green" :: Color
  pure native white "java.awt.Color.white" :: Color
  pure native new :: Int -> Color

data BasicStroke = pure native java.awt.BasicStroke where
  pure native new :: Float -> BasicStroke

data RenderingHints = native java.awt.RenderingHints where
  pure native key_antialiasing "java.awt.RenderingHints.KEY_ANTIALIASING" :: RenderingHints_Key
  pure native value_antialias_on "java.awt.RenderingHints.VALUE_ANTIALIAS_ON" :: Object

data RenderingHints_Key = pure native java.awt.RenderingHints.Key

data Graphics2D = native java.awt.Graphics2D where
  native drawLine :: Mutable s Graphics2D -> Int -> Int -> Int -> Int -> ST s ()
  native drawOval :: Mutable s Graphics2D -> Int -> Int -> Int -> Int -> ST s ()
  native fillRect :: Mutable s Graphics2D -> Int -> Int -> Int -> Int -> ST s ()
  native setColor :: Mutable s Graphics2D -> Color -> ST s ()
  native setRenderingHint :: Mutable s Graphics2D -> RenderingHints_Key -> Object -> ST s ()
  native setStroke :: Mutable s Graphics2D -> BasicStroke -> ST s ()
  native setTransform :: Mutable s Graphics2D -> Mutable s AffineTransform -> ST s ()

data ImageIO = mutable native javax.imageio.ImageIO where
  native write "javax.imageio.ImageIO.write" :: MutableIO BufferedImage -> String -> MutableIO File -> IO Bool throws IOException

drawTree :: Mutable s Graphics2D -> Mutable s AffineTransform -> Int -> ST s ()
drawTree g t i = do
  let len = 10 -- ratio of length to thickness
      shrink = 0.75
      angle = 0.3 -- radians
      i' = i - 1
  g.setTransform t
  g.drawLine 0 0 0 len
  when (i' > 0) $ do
    t.translate 0 (fromIntegral len)
    t.scale shrink shrink
    rt <- t.clone
    t.rotate angle
    rt.rotate (-angle)
    drawTree g t i'
    drawTree g rt i'

main = do
  let width = 900
      height = 800
      initScale = 20
      halfWidth = fromIntegral width / 2
  buffy <- BufferedImage.new width height BufferedImage.type_3byte_bgr
  g <- buffy.createGraphics
  g.setRenderingHint RenderingHints.key_antialiasing RenderingHints.value_antialias_on
  g.setColor Color.black
  g.fillRect 0 0 width height
  g.setColor Color.green
  t <- AffineTransform.new ()
  t.translate halfWidth (fromIntegral height)
  t.scale initScale initScale
  t.rotate pi
  drawTree g t 16
  f <- File.new "FractalTreeFrege.png"
  void $ ImageIO.write buffy "png" f


/*REXX program  computes the   forward difference   of a  list of numbers.              */
numeric digits 100                               /*ensure enough accuracy (decimal digs)*/
parse arg e ',' N                                /*get a list:  ε1 ε2 ε3 ε4 ··· , order */
if e==''  then e=90 47 58 29 22 32 55 5 55 73    /*Not specified?  Then use the default.*/
#=words(e)                                       /*#  is the number of elements in list.*/
                                                 /* [↓]  assign list numbers to @ array.*/
   do i=1  for #;  @.i=word(e, i)/1;  end /*i*/  /*process each number one at a time.   */
                                                 /* [↓]  process the optional order.    */
if N==''  then parse value 0 # # with bot top N  /*define the default  order  range.    */
          else parse var N bot 1 top             /*Not specified?  Then use only 1 order*/
say right(#  'numbers:', 44)  e                  /*display the header title   and  ···  */
say left('', 44)copies('─', length(e)+2)         /*   "     "     "   fence.            */
                                                 /* [↓]  where da rubber meets da road. */
      do o=bot  to top;        do r=1  for #;  !.[email protected].r;     end /*r*/;        $=
        do j=1  for o; d=!.j;  do k=j+1  to #; parse value !.k !.k-d with d !.k; end /*k*/
        end   /*j*/
                               do i=o+1  to #; $=$ !.i/1;   end /*i*/
      if $==''  then $=' [null]'
      say right(o, 7)th(o)'─order forward difference vector ='     $
      end     /*o*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
th: procedure; x=abs(arg(1)); return word('th st nd rd',1+x//10*(x//100%10\==1)*(x//10<4))


# Project : Forward difference

s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]
for p = 1 to 9
      s = fwddiff(s)
      showarray(s)
next

func fwddiff(s)
        for j=1 to len(s)-1
             s[j] = s[j+1]-s[j]
        next
        n = len(s)
        del(s, n)
        return s

func showarray(vect)
        see "{"
        svect = ""
        for n = 1 to len(vect)
              svect = svect + vect[n] + ", "
        next
        svect = left(svect, len(svect) - 2)
        see svect
        see "}" + nl


// Draw Fractal Tree in Frink

// Define the tree function
FractalTree[x1, y1, angleval, lengthval, graphicsobject] :=
{
   if lengthval > 1
   {
      // Define current line end points (x2 and y2)
      x2 = x1 + ((cos[angleval degrees]) * lengthval)
      y2 = y1 + ((sin[angleval degrees]) * lengthval)
      // Draw line - notice that graphicsobject is the graphics object passed into the function.
      graphicsobject.line[x1,y1,x2,y2]

      // Calculate branches. You can change the lengthval multiplier factor and angleval summand to create different trees
      FractalTree[x2, y2, angleval - 20, lengthval * 0.7, graphicsobject]
      FractalTree[x2, y2, angleval + 20, lengthval * 0.7, graphicsobject]
   }
}

// Create graphics object
g = new graphics

// Start the recursive function. In Frink, a -90° angle moves from the bottom of the screen to the top.
FractalTree[0, 0, -90, 30, g]

// Show the final tree
g.show[]


package main

// Files required to build supporting package raster are found in:
// * Bitmap
// * Grayscale image
// * Xiaolin Wu's line algorithm
// * Write a PPM file

import (
    "math"
    "raster"
)

const (
    width  = 400
    height = 300
    depth  = 8
    angle  = 12
    length = 50
    frac   = .8
)

func main() {
    g := raster.NewGrmap(width, height)
    ftree(g, width/2, height*9/10, length, 0, depth)
    g.Bitmap().WritePpmFile("ftree.ppm")
}

func ftree(g *raster.Grmap, x, y, distance, direction float64, depth int) {
    x2 := x + distance*math.Sin(direction*math.Pi/180)
    y2 := y - distance*math.Cos(direction*math.Pi/180)
    g.AaLine(x, y, x2, y2)
    if depth > 0 {
        ftree(g, x2, y2, distance*frac, direction-angle, depth-1)
        ftree(g, x2, y2, distance*frac, direction+angle, depth-1)
    }
}


def dif(s)
  s.each_cons(2).collect { |x, y| y - x }
end

def difn(s, n)
  n.times.inject(s) { |s, | dif(s) }
end


def fdiff(xs: List[Int]) = (xs.tail, xs).zipped.map(_ - _)

def fdiffn(i: Int, xs: List[Int]): List[Int] = if (i == 1) fdiff(xs) else fdiffn(i - 1, fdiff(xs))


(define (forward-diff lst)
  (if (or (null? lst) (null? (cdr lst)))
      '()
      (cons (- (cadr lst) (car lst))
            (forward-diff (cdr lst)))))

(define (nth-forward-diff n xs)
  (if (= n 0)
      xs
      (nth-forward-diff (- n 1)
                        (forward-diff xs))))


import Graphics.Gloss

type Model = [Picture -> Picture]

fractal :: Int -> Model -> Picture -> Picture
fractal n model pict = pictures $ take n $ iterate (mconcat model) pict

tree1 _ = fractal 10 branches $ Line [(0,0),(0,100)]
  where branches = [ Translate 0 100 . Scale 0.75 0.75 . Rotate 30
                   , Translate 0 100 . Scale 0.5 0.5 . Rotate (-30) ]

main = animate (InWindow "Tree" (800, 800) (0, 0)) white $ tree1 . (* 60)


procedure main()
WOpen("size=800,600", "bg=black", "fg=white") | stop("*** cannot open window")
drawtree(400,500,-90,9)
WDone()
end

link WOpen

procedure drawtree(x,y,angle,depth)
if depth > 0 then {
   x2 := integer(x + cos(dtor(angle)) * depth * 10)
   y2 := integer(y + sin(dtor(angle)) * depth * 10)
   DrawLine(x,y,x2,y2)
   drawtree(x2,y2,angle-20, depth-1)
   drawtree(x2,y2,angle+20, depth-1)
   }
return
end


$ include "seed7_05.s7i";

const func array integer: forwardDifference (in array integer: data) is func
  result
    var array integer: diffResult is 0 times 0;
  local
    var integer: index is 0;
  begin
    for index range 1 to pred(length(data)) do
      diffResult &:= -data[index] + data[succ(index)];
    end for;
  end func;

const proc: main is func
  local
    var array integer: data is [] (90, 47, 58, 29, 22, 32, 55, 5, 55, 73);
    var integer: level is 0;
    var integer: number is 0;
    var boolean: firstElement is TRUE;
  begin
    for level range 0 to length(data) do
      firstElement := TRUE;
      for number range data do
        if not firstElement then
          write(", ");
        end if;
        firstElement := FALSE;
        write(number);
      end for;
      writeln;
      data := forwardDifference(data);
    end for;
  end func;


forwardDifference(x(1), n) := forwardDifferenceHelper(x, n, [x]);

forwardDifferenceHelper(x(1), n, result(2)) :=
	let
		difference := tail(x) - x[1 ... size(x) - 1];
	in
	result when n = 0 or size(x) = 1 else
	forwardDifferenceHelper(difference, n - 1, result ++ [difference]);


[email protected](Sequence traits) forwardDifference
[
  s allButFirst with: s allButLast collect: #- `er
].

[email protected](Sequence traits) forwardDifference
"Without creating two intermediate throwaway Sequences."
[
  result ::= s allButFirst.
  result doWithIndex: [| :nextValue :index | result at: index infect: [| :oldValue | oldValue - (s at: index)].
  result
].

[email protected](Sequence traits) forwardDifference: n
[
  (0 below: n) inject: s into: [| :seq :_ | seq forwardDifference]
].


require'gl2'
coinsert'jgl2'

L0=: 50           NB. initial length
A0=: 1r8p1        NB. initial angle: pi divided by 8
dL=: 0.9          NB. shrink factor for length
dA=: 0.75         NB. shrink factor for angle
N=: 14            NB. number of branches

L=: L0*dL^1+i.N  NB. lengths of line segments

NB. relative angles of successive line segments
A=: A0*(dA^i.N) +/\@:*("1) _1 ^ #:i.2 ^ N

NB. end points for each line segment
P=: 0 0+/\@,"2 +.*.inv (L0,0),"2 L,"0"1 A

wd {{)n
 pc P closeok;
 setp wh 480 640;
 cc C isidraw flush;
 pshow;
}}

gllines <.(10 + ,/"2 P-"1<./,/P)


import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;

public class FractalTree extends JFrame {

    public FractalTree() {
        super("Fractal Tree");
        setBounds(100, 100, 800, 600);
        setResizable(false);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    private void drawTree(Graphics g, int x1, int y1, double angle, int depth) {
        if (depth == 0) return;
        int x2 = x1 + (int) (Math.cos(Math.toRadians(angle)) * depth * 10.0);
        int y2 = y1 + (int) (Math.sin(Math.toRadians(angle)) * depth * 10.0);
        g.drawLine(x1, y1, x2, y2);
        drawTree(g, x2, y2, angle - 20, depth - 1);
        drawTree(g, x2, y2, angle + 20, depth - 1);
    }

    @Override
    public void paint(Graphics g) {
        g.setColor(Color.BLACK);
        drawTree(g, 400, 500, -90, 9);
    }

    public static void main(String[] args) {
        new FractalTree().setVisible(true);
    }
}


Array extend [
    difference [
        ^self allButFirst with: self allButLast collect: [ :a :b | a - b ]
    ]

    nthOrderDifference: n [
        ^(1 to: n) inject: self into: [ :old :unused | old difference ]
    ]
]

s := #(90 47 58 29 22 32 55 5 55 73)
1 to: s size - 1 do: [ :i |
    (s nthOrderDifference: i) printNl ]


WITH RECURSIVE
T0 (N, ITEM, LIST, NEW_LIST) AS
(
    SELECT 1,
           NULL,
           '90,47,58,29,22,32,55,5,55,73' || ',',
           NULL
     UNION ALL
    SELECT CASE
               WHEN SUBSTR(LIST, INSTR(LIST, ',') + 1, LENGTH(LIST)) = ''
               THEN N + 1
               ELSE N
           END,
           CASE
               WHEN SUBSTR(LIST, INSTR(LIST, ',') + 1, LENGTH(LIST)) <> ''
               THEN SUBSTR(LIST, 1, INSTR(LIST, ',') - 1)
               ELSE NULL
           END,
           CASE
               WHEN SUBSTR(LIST, INSTR(LIST, ',') + 1, LENGTH(LIST)) = ''
               THEN IFNULL(NEW_LIST || (SUBSTR(LIST, 1, INSTR(LIST, ',') - 1) - ITEM) || ',', '')
               ELSE SUBSTR(LIST, INSTR(LIST, ',') + 1, LENGTH(LIST))
           END,
           CASE
               WHEN SUBSTR(LIST, INSTR(LIST, ',') + 1, LENGTH(LIST)) <> ''
               THEN IFNULL(NEW_LIST, '') || IFNULL((SUBSTR(LIST, 1, INSTR(LIST, ',') - 1) - ITEM) || ',', '')
               ELSE NULL
           END
      FROM T0
     WHERE INSTR(LIST, ',') > 0
)
SELECT N,
       TRIM(LIST, ',') LIST
  FROM T0
 WHERE NEW_LIST IS NULL
   AND LIST <> ''
 ORDER BY N;


<html>
<body>
<canvas id="canvas" width="600" height="500"></canvas>

<script type="text/javascript">
var elem = document.getElementById('canvas');
var context = elem.getContext('2d');

context.fillStyle = '#C0C0C0';
context.lineWidth = 1;

var deg_to_rad = Math.PI / 180.0;
var depth = 9;

function drawLine(x1, y1, x2, y2, brightness){
  context.moveTo(x1, y1);
  context.lineTo(x2, y2);
}

function drawTree(x1, y1, angle, depth){
  if (depth !== 0){
    var x2 = x1 + (Math.cos(angle * deg_to_rad) * depth * 10.0);
    var y2 = y1 + (Math.sin(angle * deg_to_rad) * depth * 10.0);
    drawLine(x1, y1, x2, y2, depth);
    drawTree(x2, y2, angle - 20, depth - 1);
    drawTree(x2, y2, angle + 20, depth - 1);
  }
}

context.beginPath();
drawTree(300, 500, -90, depth);
context.closePath();
context.stroke();
</script>

</body>
</html>


fun forward_difference xs = ListPair.map op- (tl xs, xs)

fun nth_forward_difference n xs =
  if n = 0 then
    xs
  else
    nth_forward_difference (n-1) (forward_difference xs)


func forwardsDifference<T: SignedNumeric>(of arr: [T]) -> [T] {
  return zip(arr.dropFirst(), arr).map({ $0.0 - $0.1 })
}

func nthForwardsDifference<T: SignedNumeric>(of arr: [T], n: Int) -> [T] {
  assert(n >= 0)

  switch (arr, n) {
  case ([], _):
    return []
  case let (arr, 0):
    return arr
  case let (arr, i):
    return nthForwardsDifference(of: forwardsDifference(of: arr), n: i - 1)
  }
}

for diff in (0...9).map({ nthForwardsDifference(of: [90, 47, 58, 29, 22, 32, 55, 5, 55, 73], n: $0) }) {
  print(diff)
}


proc do_fwd_diff {list} {
    set previous [lindex $list 0]
    set new [list]
    foreach current [lrange $list 1 end] {
        lappend new [expr {$current - $previous}]
        set previous $current
    }
    return $new
}

proc fwd_diff {list order} {
    while {$order >= 1} {
        set list [do_fwd_diff $list]
        incr order -1
    }
    return $list
}

set a {90.5 47 58 29 22 32 55 5 55 73.5}

for {set order 0} {$order <= 10} {incr order} {
    puts [format "%d\t%s" $order [fwd_diff $a $order]]
}


# width and height define the outer dimensions;
# len defines the trunk size;
# scale defines the branch length relative to the trunk;
def main(width; height; len; scale):

  def PI: (1|atan)*4;

  def precision(n):
    def pow(k): . as $in | reduce range(0;k) as $i (1; .*$in);
    if . < 0 then - (-. | precision(n))
    else
      (10|pow(n)) as $power
    | (. * 10 * $power) | floor as $x | ($x % 10) as $r
    | ((if $r < 5 then $x else $x + 5 end) / 10 | floor) / $power
    end;

  def p2: precision(2);

  def tree(x; y; len; angle):
    if len < 1 then empty
    else
      (x + len * (angle|cos)) as $x2
    | (y + len * (angle|sin)) as $y2
    | (if len < 10 then 1 else 2 end) as $swidth
    | (if len < 10 then "blue" else "black" end) as $stroke
    | "<line x1='\(x|p2)' y1='\(y|p2)' x2='\($x2|p2)' y2='\($y2|p2)' style='stroke:\($stroke); stroke-width:\($swidth)'/>",
      tree($x2; $y2; len * scale; angle + PI / 5),
      tree($x2; $y2; len * scale; angle - PI / 5)
    end
  ;

  "<svg width='100%' height='100%' version='1.1'
        xmlns='http://www.w3.org/2000/svg'>",
        tree(width / 2; height; len; 3 * PI / 2),
  "</svg>"
;

main(1000; 1000; 400; 6/10)


const width = height = 1000.0
const trunklength = 400.0
const scalefactor = 0.6
const startingangle = 1.5 * pi
const deltaangle = 0.2 * pi

function tree(fh, x, y, len, theta)
   if len >= 1.0
       x2 = x + len * cos(theta)
       y2 = y + len * sin(theta)
       write(fh, "<line x1='$x' y1='$y' x2='$x2' y2='$y2' style='stroke:rgb(0,0,0);stroke-width:1'/>\n")
       tree(fh, x2, y2, len * scalefactor, theta + deltaangle)
       tree(fh, x2, y2, len * scalefactor, theta - deltaangle)
    end
end

outsvg = open("tree.svg", "w")
write(outsvg,
    """<?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'>\n""")

tree(outsvg, 0.5 * width, height, trunklength, startingangle)

write(outsvg, "</svg>\n") # view file tree.svg in browser


// version 1.1.2

import java.awt.Color
import java.awt.Graphics
import javax.swing.JFrame

class FractalTree : JFrame("Fractal Tree") {
    init {
        background = Color.black
        setBounds(100, 100, 800, 600)
        isResizable = false
        defaultCloseOperation = EXIT_ON_CLOSE
    }

    private fun drawTree(g: Graphics, x1: Int, y1: Int, angle: Double, depth: Int) {
        if (depth == 0) return
        val x2 = x1 + (Math.cos(Math.toRadians(angle)) * depth * 10.0).toInt()
        val y2 = y1 + (Math.sin(Math.toRadians(angle)) * depth * 10.0).toInt()
        g.drawLine(x1, y1, x2, y2)
        drawTree(g, x2, y2, angle - 20, depth - 1)
        drawTree(g, x2, y2, angle + 20, depth - 1)
    }

    override fun paint(g: Graphics) {
        g.color = Color.white
        drawTree(g, 400, 500, -90.0, 9)
    }
}

fun main(args: Array<String>) {
    FractalTree().isVisible = true
}


#import std
#import nat
#import flo

nth_diff "n" = rep"n" minus*typ


Module ForwardDifference

    Sub Main()
        Dim lNum As New List(Of Integer)(New Integer() {90, 47, 58, 29, 22, 32, 55, 5, 55, 73})
        For i As UInteger = 0 To 9
            Console.WriteLine(String.Join(" ", (From n In Difference(i, lNum) Select String.Format("{0,5}", n)).ToArray()))
        Next
        Console.ReadKey()
    End Sub

    Private Function Difference(ByVal Level As UInteger, ByVal Numbers As List(Of Integer)) As List(Of Integer)
        If Level >= Numbers.Count Then Throw New ArgumentOutOfRangeException("Level", "Level must be less than number of items in Numbers")

        For i As Integer = 1 To Level
            Numbers = (From n In Enumerable.Range(0, Numbers.Count - 1) _
                       Select Numbers(n + 1) - Numbers(n)).ToList()
        Next

        Return Numbers
    End Function

End Module


#DEFINE CTAB CHR(9)
LOCAL lcList As String, i As Integer, n As Integer
n = 10
LOCAL ARRAY aa[n]
CLEAR
lcList = "90,47,58,29,22,32,55,5,55,73"
FOR i = 1 TO n
    aa[i] = VAL(GETWORDNUM(lcList, i, ","))
ENDFOR
ShowOutput("Original", @aa)
k = n - 1
FOR i = 1 TO n - 1
    ForwardDiff(@aa)
    ShowOutput("Difference " + TRANSFORM(i), @aa)
ENDFOR

PROCEDURE ForwardDiff(a)
LOCAL i As Integer, n As Integer
n = ALEN(a)
LOCAL ARRAY b[n-1]
FOR i = 1 TO n - 1
    b[i] = a[i+1] - a[i]
ENDFOR
DIMENSION a[n-1]
ACOPY(b, a)
ENDPROC

PROCEDURE ShowOutput(lcLabel, zz)
LOCAL i As Integer, n As Integer, lcTxt As String
n = ALEN(zz)
lcTxt = lcLabel + ":" + CTAB
FOR i = 1 TO n
    lcTxt = lcTxt + TRANSFORM(zz[i]) + CTAB
ENDFOR
lcTxt = LEFT(lcTxt, LEN(lcTxt) - 1)
? lcTxt
ENDPROC


1) defining the function tree:

{def tree
 {lambda {:e     // last branch length
          :s     // trunks length
          :k     // ratio between two following branches
          :a     // rotate left
          :b}    // rotate right
  {if {< :s :e}
   then
   else M:s T:a
        {tree :e {* :k :s} :k :a :b}
        T-{+ :a :b}
        {tree :e {* :k :s} :k :a :b}
        T:b M-:s }}}

2) Calling this function generates a sequence of commands mooving a pen:
• Tθ rotates the drawing direction "θ" degrees from the previous one
• and Md draws a segment "d" pixels in this direction.

{def T {tree 1 190 {/ 2 3} 15 45}}

and produces 40995 words beginning with:

M190 T15 M126.66666666666666 T15 M84.44444444444443 T15 M56.29629629629628 T15 M37.53086419753085 T15 M25.020576131687235 T15
 M16.680384087791488 T15 M11.120256058527659 T15 M7.413504039018439 T15 M4.942336026012292 T15 M3.2948906840081946 ...

3) These words are sent to a the turtle lambdatalk primitive
which is a graphic device translating the sequence of Md and Tθ
into a sequence of SVG points x0 y0 x1 y1 ... xn yn
which will feed the points attribute of a polyline SVG element:

{svg {@ width="580px" height="580px" style="box-shadow:0 0 8px #000;"}
  {polyline
   {@ points="{turtle 230 570 180 {T}}"
      fill="transparent" stroke="#fff" stroke-width="1"
}}}

This is an abstract of the output:

<svg width="580px" height="580px" style="box-shadow:0 0 8px #000;">
  <polyline points="230 580 230 380 195 251 151 174 109 132 75 113 49 106 32 106 21 109 ...
                    ... 413 286 324 286 230 380 230 580 "
           fill="transparent" stroke="#888" stroke-width="1">
  </polyline>
</svg>

The complete ouput can be seen displayed in http://lambdaway.free.fr/lambdawalks/?view=fractal_tree


import "/fmt" for Fmt

var forwardDiff = Fn.new { |a, order|
    if (order < 0) Fiber.abort("Order must be a non-negative integer.")
    if (a.count == 0) return
    Fmt.print(" 0: $5d", a)
    if (a.count == 1) return
    if (order == 0) return
    for (o in 1..order) {
        var b = List.filled(a.count-1, 0)
        for (i in 0...b.count) b[i] = a[i+1] - a[i]
        Fmt.print("$2d: $5d", o, b)
        if (b.count == 1) return
        a = b
    }
}

forwardDiff.call([90, 47, 58, 29, 22, 32, 55, 5, 55, 73], 9)


fcn forwardDiff(lst){
   if(lst.len()<2)
      return(T);
      return(T(lst[1]-lst[0]).extend(forwardDiff(lst[1,*])))
}
fcn nthForwardDiff(n,xs){
   if(n==0)
      return(xs);
      return(nthForwardDiff(n-1,forwardDiff(xs))) // tail recursion
}


 NoMainWin
sw = 640 :   sh = 480
WindowWidth  = sw+8 : WindowHeight = sh+31
UpperLeftX = (DisplayWidth -sw)/2
UpperLeftY = (DisplayHeight-sh)/2
Open"Fractal Tree" For Graphics_nf_nsb As #g
#g "Down; Color darkgreen; TrapClose halt"
h$ = "#g"

'initial assignments
initAngle = Acs(-1)*1.5 'radian equivalent of 270 degrees
    theta = 29 * (Acs(-1)/180) 'convert 29 degrees to radians
   length = 110 'length in pixels
    depth = 25   'max recursion depth
    'draw the tree
    Call tree h$, 320, 470, initAngle, theta, length, depth
    #g "Flush; when leftButtonDown halt" 'L-click to exit
    Wait

Sub halt handle$
    Close #handle$
    End
End Sub

Sub tree h$, x, y, initAngle, theta, length, depth
    Scan
    newX = Cos(initAngle) * length + x
    newY = Sin(initAngle) * length + y
    #h$ "Line ";x;" ";y;" ";newX;" ";newY
    length = length * .78
    depth = depth - 1
    If depth > 0 Then
        Call tree h$, newX, newY, initAngle-theta, theta, length, depth
        Call tree h$, newX, newY, initAngle+theta, theta, length, depth
    End If
End Sub


10 DATA 9,0,1,2,4,7,4,2,1,0
20 LET p=1
30 READ n: DIM b(n)
40 FOR i=1 TO n
50 READ b(i)
60 NEXT i
70 FOR j=1 TO p
80 FOR i=1 TO n-j
90 LET b(i)=b(i+1)-b(i)
100 NEXT i
110 NEXT j
120 FOR i=1 TO n-p
130 PRINT b(i);" ";
140 NEXT i


----------------------------------------
-- Creates an image of a fractal tree
-- @param {integer} width
-- @param {integer} height
-- @param {integer} fractalDepth
-- @param {integer|float} initSize
-- @param {float} spreadAngle
-- @param {float} [scaleFactor=1.0]
-- @return {image}
----------------------------------------
on fractalTree (width, height, fractalDepth, initSize, spreadAngle, scaleFactor)
  if voidP(scaleFactor) then scaleFactor = 1.0
  img = image(width, height, 24)
  img.fill(img.rect, rgb(0,0,0))
  _drawTree(img, width/2, height, -PI/2, fractalDepth, initSize, spreadAngle, scaleFactor)
  return img
end

on _drawTree (img, x1, y1, angle, depth, size, spreadAngle, scaleFactor)
  if (depth) then
    x2 = x1 + cos(angle)*depth*size
    y2 = y1 + sin(angle)*depth*size
    img.draw(x1, y1, x2, y2, [#color:rgb(255,255,255)])
    _drawTree(img, x2, y2, angle-spreadAngle, depth-1, size*ScaleFactor, spreadAngle, scaleFactor)
    _drawTree(img, x2, y2, angle+spreadAngle, depth-1, size*ScaleFactor, spreadAngle, scaleFactor)
  end if
end


to tree :depth :length :scale :angle
  if :depth=0 [stop]
  setpensize round :depth/2
  forward :length
  right :angle
  tree :depth-1 :length*:scale :scale :angle
  left 2*:angle
  tree :depth-1 :length*:scale :scale :angle
  right :angle
  back :length
end

clearscreen
tree 10 80 0.7 30


g, angle = love.graphics, 26 * math.pi / 180
wid, hei = g.getWidth(), g.getHeight()
function rotate( x, y, a )
  local s, c = math.sin( a ), math.cos( a )
  local a, b = x * c - y * s, x * s + y * c
  return a, b
end
function branches( a, b, len, ang, dir )
  len = len * .76
  if len < 5 then return end
  g.setColor( len * 16, 255 - 2 * len , 0 )
  if dir > 0 then ang = ang - angle
  else ang = ang + angle
  end
  local vx, vy = rotate( 0, len, ang )
  vx = a + vx; vy = b - vy
  g.line( a, b, vx, vy )
  branches( vx, vy, len, ang, 1 )
  branches( vx, vy, len, ang, 0 )
end
function createTree()
  local lineLen = 127
  local a, b = wid / 2, hei - lineLen
  g.setColor( 160, 40 , 0 )
  g.line( wid / 2, hei, a, b )
  branches( a, b, lineLen, 0, 1 )
  branches( a, b, lineLen, 0, 0 )
end
function love.load()
  canvas = g.newCanvas( wid, hei )
  g.setCanvas( canvas )
  createTree()
  g.setCanvas()
end
function love.draw()
  g.draw( canvas )
end


fractalTree[
  pt : {_, _}, \[Theta]orient_: \[Pi]/2, \[Theta]sep_: \[Pi]/9,
  depth_Integer: 9] := Module[{pt2},
  If[depth == 0, Return[]];
  pt2 = pt + {Cos[\[Theta]orient], Sin[\[Theta]orient]}*depth;
  DeleteCases[
   [email protected]{
     Line[{pt, pt2}],
     fractalTree[pt2, \[Theta]orient - \[Theta]sep, \[Theta]sep,
      depth - 1],
     fractalTree[pt2, \[Theta]orient + \[Theta]sep, \[Theta]sep,
      depth - 1]
     },
   Null
   ]
  ]
Graphics[fractalTree[{0, 0}, \[Pi]/2, \[Pi]/9]]


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

import java.awt.Color
import java.awt.Graphics
import javax.swing.JFrame

class RFractalTree public extends JFrame
  properties constant
    isTrue  = (1 == 1)
    isFalse = \isTrue
  -- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
  method RFractalTree() public
    super('Fractal Tree')
    setBounds(100, 100, 800, 600)
    setResizable(isFalse)
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    return
  -- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
  method drawTree(g = Graphics, x1 = int, y1 = int, angle = double, depth = int) private
    if depth \= 0 then do
      x2 = x1 + (int Math.cos(Math.toRadians(angle)) * depth * 10.0)
      y2 = y1 + (int Math.sin(Math.toRadians(angle)) * depth * 10.0)
      g.drawLine(x1, y1, x2, y2)
      drawTree(g, x2, y2, angle - 20, depth - 1)
      drawTree(g, x2, y2, angle + 20, depth - 1)
      end
    return
  -- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
  method paint(g = Graphics) public
    g.setColor(Color.BLACK)
    drawTree(g, 400, 500, -90, 9)
    return
  -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  method main(args = String[])public static
    RFractalTree().setVisible(isTrue)
    return


import math
import strformat

const
  Width = 1000
  Height = 1000
  TrunkLength = 400
  ScaleFactor = 0.6
  StartingAngle = 1.5 * PI
  DeltaAngle = 0.2 * PI

proc drawTree(outfile: File; x, y, len, theta: float) =
  if len >= 1:
    let x2 = x + len * cos(theta)
    let y2 = y + len * sin(theta)
    outfile.write(
      fmt"<line x1='{x}' y1='{y}' x2='{x2}' y2='{y2}' style='stroke:white;stroke-width:1'/>\n")
    outfile.drawTree(x2, y2, len * ScaleFactor, theta + DeltaAngle)
    outFile.drawTree(x2, y2, len * ScaleFactor, theta - DeltaAngle)

let outsvg = open("tree.svg", fmWrite)
outsvg.write("""<?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'>\n
                <rect width="100%" height="100%" fill="black"/>\n""")

outsvg.drawTree(0.5 * Width, Height, TrunkLength, StartingAngle)
outsvg.write("</svg>\n")   # View file tree.svg in browser.


#directory "+cairo"
#load "bigarray.cma"
#load "cairo.cma"

let img_name = "/tmp/fractree.png"
let width  = 480
let height = 640

let level = 9
let line_width = 4.0

let color = (1.0, 0.5, 0.0)

let pi = 4.0 *. atan 1.0

let angle_split = pi *. 0.12
let angle_rand  = pi *. 0.12

let () =
  Random.self_init();
  let surf = Cairo.image_surface_create Cairo.FORMAT_RGB24 ~width ~height in
  let ctx = Cairo.create surf in
  Cairo.set_antialias ctx Cairo.ANTIALIAS_SUBPIXEL;
  Cairo.set_line_cap ctx Cairo.LINE_CAP_ROUND;

  let draw_line (x,y) (dx,dy) =
    Cairo.move_to ctx x  (float height -. y);
    Cairo.line_to ctx dx (float height -. dy);
    Cairo.stroke ctx;
  in
  let set_color (r,g,b) v =
    Cairo.set_source_rgb ctx ~red:(r *. v) ~green:(g *. v) ~blue:(b *. v);
  in
  let trans_pos (x,y) len angle =
    let _x = cos angle
    and _y = sin angle in
    (x +. (_x *. len),
     y +. (_y *. len))
  in

  let rec loop ~level ~pos ~line_width ~line_len
               ~angle ~angle_split ~angle_rand ~intc =
    if level > 0 then begin
      (* draw the current segment *)
      Cairo.set_line_width ctx line_width;
      set_color color intc;
      let pos_to = trans_pos pos line_len angle in
      draw_line pos pos_to;
      (* evolution of the parameters *)
      let line_width = line_width *. 0.8
      and line_len   = line_len   *. 0.62
      and angle_split = angle_split *. 1.02
      and angle_rand  = angle_rand  *. 1.02
      and intc = intc *. 0.9
      in
      let next_loop =
        loop ~level:(pred level) ~pos:pos_to ~intc
             ~line_width ~line_len ~angle_split ~angle_rand
      in
      (* split *)
      let angle_left  = angle +. angle_split +. Random.float angle_rand
      and angle_right = angle -. angle_split -. Random.float angle_rand
      in
      next_loop ~angle:angle_left;
      next_loop ~angle:angle_right
    end
  in

  let pos = (float width *. 0.5, float height *. 0.1)
  and line_len = float height *. 0.3
  in
  loop ~level ~pos ~angle:(pi /. 2.0)
       ~angle_split ~angle_rand
       ~line_width ~line_len ~intc:1.0;

  Cairo_png.surface_write_to_file surf img_name
  (*Cairo_png.surface_write_to_channel surf stdout*)


F xor(a, b)
   R (a & !b) | (b & !a)

F ha(a, b)
   R (xor(a, b), a & b)

F fa(a, b, ci)
   V (s0, c0) = ha(ci, a)
   V (s1, c1) = ha(s0, b)
   R (s1, c0 | c1)

F fa4(a, b)
   V width = 4
   V ci = [0B] * width
   V co = [0B] * width
   V s = [0B] * width
   L(i) 0 .< width
      (s[i], co[i]) = fa(a[i], b[i], I i != 0 {co[i - 1]} E 0)
   R (s, co.last)

F int2bus(n, width = 4)
   R reversed(bin(n).zfill(width)).map(c -> Int(c))

F bus2int(b)
   R sum(enumerate(b).filter2((i, bit) -> bit).map2((i, bit) -> 1 << i))

V width = 4
V tot = [0B] * (width + 1)
L(a) 0 .< 2 ^ width
   L(b) 0 .< 2 ^ width
      V (ta, tlast) = fa4(int2bus(a), int2bus(b))
      L(i) 0 .< width
         tot[i] = ta[i]
      tot[width] = tlast
      assert(a + b == bus2int(tot), ‘totals don't match: #. + #. != #.’.format(a, b, String(tot)))


\\ Fractal tree (w/recursion)
\\ 4/10/16 aev
plotline(x1,y1,x2,y2)={plotmove(0, x1,y1);plotrline(0,x2-x1,y2-y1);}

plottree(x,y,a,d)={
my(x2,y2,d2r=Pi/180.0,a1=a*d2r,d1);
if(d<=0, return(););
if(d>0, d1=d*10.0;
    x2=x+cos(a1)*d1;
    y2=y+sin(a1)*d1;
    plotline(x,y,x2,y2);
    plottree(x2,y2,a-20,d-1);
    plottree(x2,y2,a+20,d-1),
    return();
  );
}

FractalTree(depth,size)={
my(dx=1,dy=0,ttlb="Fractal Tree, depth ",ttl=Str(ttlb,depth));
print1(" *** ",ttl); print(", size ",size);
plotinit(0);
plotcolor(0,6); \\green
plotscale(0, -size,size, 0,size);
plotmove(0, 0,0);
plottree(0,0,90,depth);
plotdraw([0,size,size]);
}

{\\ Executing:
FractalTree(9,500);     \\FracTree1.png
FractalTree(12,1100);   \\FracTree2.png
FractalTree(15,1500);   \\FracTree3.png
}


DEFINE Bit="BYTE"

TYPE FourBit=[Bit b0,b1,b2,b3]

Bit FUNC Not(Bit a)
RETURN (1-a)

Bit FUNC MyXor(Bit a,b)
RETURN ((Not(a) AND b) OR (a AND Not(b)))

Bit FUNC HalfAdder(Bit a,b Bit POINTER c)
  c^=a AND b
RETURN (MyXor(a,b))

Bit FUNC FullAdder(Bit a,b,c0 Bit POINTER c)
  Bit s1,c1,s2,c2

  s1=HalfAdder(a,c0,@c1)
  s2=HalfAdder(b,s1,@c2)

  c^=c1 OR c2
RETURN (s2)

PROC FourBitAdder(FourBit POINTER a,b,s Bit POINTER c)
  Bit c1,c2,c3

  s.b3=FullAdder(a.b3,b.b3,0,@c3)
  s.b2=FullAdder(a.b2,b.b2,c3,@c2)
  s.b1=FullAdder(a.b1,b.b1,c2,@c1)
  s.b0=FullAdder(a.b0,b.b0,c1,c)
RETURN

PROC InitFourBit(BYTE a FourBit POINTER res)
  res.b3=a&1 a==RSH 1
  res.b2=a&1 a==RSH 1
  res.b1=a&1 a==RSH 1
  res.b0=a&1
RETURN

PROC PrintFourBit(FourBit POINTER a)
  PrintB(a.b0) PrintB(a.b1)
  PrintB(a.b2) PrintB(a.b3)
RETURN

PROC Main()
  FourBit a,b,s
  Bit c
  BYTE i,v

  FOR i=1 TO 20
  DO
    v=Rand(16) InitFourBit(v,a)
    v=Rand(16) InitFourBit(v,b)

    FourBitAdder(a,b,s,@c)

    PrintFourBit(a) Print(" + ")
    PrintFourBit(b) Print(" = ")
    PrintFourBit(s) Print(" Carry=")
    PrintBE(c)
  OD
RETURN


type Four_Bits is array (1..4) of Boolean;

procedure Half_Adder (Input_1, Input_2 : Boolean; Output, Carry : out Boolean) is
begin
   Output := Input_1 xor Input_2;
   Carry  := Input_1 and Input_2;
end Half_Adder;

procedure Full_Adder (Input_1, Input_2 : Boolean; Output : out Boolean; Carry : in out Boolean) is
   T_1, T_2, T_3 : Boolean;
begin
   Half_Adder (Input_1, Input_2, T_1, T_2);
   Half_Adder (Carry, T_1, Output, T_3);
   Carry := T_2 or T_3;
end Full_Adder;

procedure Four_Bits_Adder (A, B : Four_Bits; C : out Four_Bits; Carry : in out Boolean) is
begin
   Full_Adder (A (4), B (4), C (4), Carry);
   Full_Adder (A (3), B (3), C (3), Carry);
   Full_Adder (A (2), B (2), C (2), Carry);
   Full_Adder (A (1), B (1), C (1), Carry);
end Four_Bits_Adder;


use GD::Simple;

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

my $img = GD::Simple->new($width,$height);
$img->fgcolor('black');
$img->penSize(1,1);

tree($width/2, $height, $length, 270);

print $img->png;

sub tree
{
        my ($x, $y, $len, $angle) = @_;

        return if $len < 1;

        $img->moveTo($x,$y);
        $img->angle($angle);
        $img->line($len);

        ($x, $y) = $img->curPos();

        tree($x, $y, $len*$scale, $angle+35);
        tree($x, $y, $len*$scale, $angle-35);
}


A := 13
B := 9
N := FourBitAdd(A, B)
MsgBox, % A " + " B ":`n"
	. GetBin4(A) " + " GetBin4(B) " = " N.S " (Carry = " N.C ")"
return

Xor(A, B) {
	return (~A & B) | (A & ~B)
}

HalfAdd(A, B) {
	return {"S": Xor(A, B), "C": A & B}
}

FullAdd(A, B, C=0) {
	X := HalfAdd(A, C)
	Y := HalfAdd(B, X.S)
	return {"S": Y.S, "C": X.C | Y.C}
}

FourBitAdd(A, B, C=0) {
	A := GetFourBits(A)
	B := GetFourBits(B)
	X := FullAdd(A[4], B[4], C)
	Y := FullAdd(A[3], B[3], X.C)
	W := FullAdd(A[2], B[2], Y.C)
	Z := FullAdd(A[1], B[1], W.C)
	return {"S": Z.S W.S Y.S X.S, "C": Z.C}
}

GetFourBits(N) {
	if (N < 0 || N > 15)
		return -1
	return StrSplit(GetBin4(N))
}

GetBin4(N) {
	Loop 4
		Res := Mod(N, 2) Res, N := N >> 1
	return, Res
}


--
-- demo\rosetta\FractalTree.exw
-- ============================
--
with javascript_semantics
include pGUI.e

Ihandle dlg, canvas
cdCanvas cddbuffer, cdcanvas

procedure drawTree(integer level, atom angle, len, integer x, y)
    integer xn = x + floor(len*cos(angle)),
            yn = y + floor(len*sin(angle)),
            red = 255-level*8,
            green = level*12+100
    cdCanvasSetForeground(cddbuffer, red*#10000 + green*#100)
    cdCanvasSetLineWidth(cddbuffer,floor(5-level/3))
    cdCanvasLine(cddbuffer, x, 480-y, xn, 480-yn)
    if level<12 then
        drawTree(level+1, angle-0.4, len*0.8, xn, yn)   --left
        drawTree(level+1, angle+0.1, len*0.8, xn, yn)   --right
    end if
end procedure

function redraw_cb(Ihandle /*ih*/, integer /*posx*/, /*posy*/)
    cdCanvasActivate(cddbuffer)
    cdCanvasClear(cddbuffer)
    drawTree(0, -PI/2.0, 80.0, 360, 460)
    cdCanvasFlush(cddbuffer)
    return IUP_DEFAULT
end function

function map_cb(Ihandle ih)
    cdcanvas = cdCreateCanvas(CD_IUP, ih)
    cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas)
    cdCanvasSetBackground(cddbuffer, CD_PARCHMENT)
    return IUP_DEFAULT
end function

procedure main()
    IupOpen()

    canvas = IupCanvas("RASTERSIZE=640x480")
    IupSetCallbacks(canvas, {"MAP_CB", Icallback("map_cb"),
                             "ACTION", Icallback("redraw_cb")})

    dlg = IupDialog(canvas,"RESIZE=NO")
    IupSetAttribute(dlg, "TITLE", "Fractal Tree")

    IupShow(dlg)
    if platform()!=JS then
        IupMainLoop()
        IupClose()
    end if
end procedure

main()


Func _NOT($_A)
	Return (Not $_A) *1
EndFunc  ;==>_NOT

Func _AND($_A, $_B)
	Return BitAND($_A, $_B)
EndFunc  ;==>_AND

Func _OR($_A, $_B)
	Return BitOR($_A, $_B)
EndFunc  ;==>_OR

Func _XOR($_A, $_B)
	Return _OR( _
		_AND( $_A, _NOT($_B) ), _
		_AND( _NOT($_A), $_B) )
EndFunc  ;==>_XOR

Func _HalfAdder($_A, $_B, ByRef $_CO)
	$_CO = _AND($_A, $_B)
	Return _XOR($_A, $_B)
EndFunc  ;==>_HalfAdder

Func _FullAdder($_A, $_B, $_CI, ByRef $_CO)
	Local $CO1, $CO2, $Q1, $Q2
	$Q1 = _HalfAdder($_A, $_B, $CO1)
	$Q2 = _HalfAdder($Q1, $_CI, $CO2)
	$_CO = _OR($CO2, $CO1)
	Return $Q2
EndFunc  ;==>_FullAdder

Func _4BitAdder($_A1, $_A2, $_A3, $_A4, $_B1, $_B2, $_B3, $_B4, $_CI, ByRef $_CO)
	Local $CO1, $CO2, $CO3, $CO4, $Q1, $Q2, $Q3, $Q4
	$Q1 = _FullAdder($_A4, $_B4, $_CI, $CO1)
	$Q2 = _FullAdder($_A3, $_B3, $CO1, $CO2)
	$Q3 = _FullAdder($_A2, $_B2, $CO2, $CO3)
	$Q4 = _FullAdder($_A1, $_B1, $CO3, $CO4)
	$_CO = $CO4
	Return $Q4 & $Q3 & $Q2 & $Q1
EndFunc  ;==>_4BitAdder


<?php
header("Content-type: image/png");

$width = 512;
$height = 512;
$img = imagecreatetruecolor($width,$height);
$bg = imagecolorallocate($img,255,255,255);
imagefilledrectangle($img, 0, 0, $width, $width, $bg);

$depth = 8;
function drawTree($x1, $y1, $angle, $depth){

    global $img;

    if ($depth != 0){
        $x2 = $x1 + (int)(cos(deg2rad($angle)) * $depth * 10.0);
        $y2 = $y1 + (int)(sin(deg2rad($angle)) * $depth * 10.0);

        imageline($img, $x1, $y1, $x2, $y2, imagecolorallocate($img,0,0,0));

        drawTree($x2, $y2, $angle - 20, $depth - 1);
        drawTree($x2, $y2, $angle + 20, $depth - 1);
    }
}

drawTree($width/2, $height, -90, $depth);

imagepng($img);
imagedestroy($img);
?>


100 S$ = "1100 + 1100 = " : GOSUB 400
110 S$ = "1100 + 1101 = " : GOSUB 400
120 S$ = "1100 + 1110 = " : GOSUB 400
130 S$ = "1100 + 1111 = " : GOSUB 400
140 S$ = "1101 + 0000 = " : GOSUB 400
150 S$ = "1101 + 0001 = " : GOSUB 400
160 S$ = "1101 + 0010 = " : GOSUB 400
170 S$ = "1101 + 0011 = " : GOSUB 400
180 END

400 A0 = VAL(MID$(S$, 4, 1))
410 A1 = VAL(MID$(S$, 3, 1))
420 A2 = VAL(MID$(S$, 2, 1))
430 A3 = VAL(MID$(S$, 1, 1))
440 B0 = VAL(MID$(S$, 11, 1))
450 B1 = VAL(MID$(S$, 10, 1))
460 B2 = VAL(MID$(S$, 9, 1))
470 B3 = VAL(MID$(S$, 8, 1))
480 GOSUB 600
490 PRINT S$;

REM 4 BIT PRINT
500 PRINT C;S3;S2;S1;S0
510 RETURN

REM 4 BIT ADD
REM  ADD A3 A2 A1 A0 TO B3 B2 B1 B0
REM  RESULT IN S3 S2 S1 S0
REM  CARRY IN C
600 C = 0
610 A = A0 : B = B0 : GOSUB 700 : S0 = S
620 A = A1 : B = B1 : GOSUB 700 : S1 = S
630 A = A2 : B = B2 : GOSUB 700 : S2 = S
640 A = A3 : B = B3 : GOSUB 700 : S3 = S
650 RETURN

REM FULL ADDER
REM  ADD A + B + C
REM  RESULT IN S
REM  CARRY IN C
700 BH = B : B = C : GOSUB 800 : C1 = C
710 A = S : B = BH : GOSUB 800 : C2 = C
720 C = C1 OR C2
730 RETURN

REM HALF ADDER
REM  ADD A + B
REM  RESULT IN S
REM  CARRY IN C
800 GOSUB 900 : S = C
810 C = A AND B
820 RETURN

REM XOR GATE
REM  A XOR B
REM  RESULT IN C
900 C = A AND NOT B
910 D = B AND NOT A
920 C = C OR D
930 RETURN


@echo off
setlocal enabledelayedexpansion

:: ":main" is where all the non-logic-gate stuff happens
:main
:: User input two 4-digit binary numbers
:: There is no error checking for these numbers, however if the first 4 digits of both inputs are in binary...
:: The program will use them. All non-binary numbers are treated as 0s, but having less than 4 digits will crash it
set /p "input1=First 4-Bit Binary Number: "
set /p "input2=Second 4-Bit Binary Number: "

:: Put the first 4 digits of the binary numbers and separate them into "A[]" for input A and "B[]" for input B
for /l %%i in (0,1,3) do (
  set A%%i=!input1:~%%i,1!
  set B%%i=!input2:~%%i,1!
)

:: Run the 4-bit Adder with "A[]" and "B[]" as parameters. The program supports a 9th parameter for a Carry input
call:_4bitAdder %A3% %A2% %A1% %A0% %B3% %B2% %B1% %B0% 0

:: Display the answer and exit
echo %input1% + %input2% = %outputC%%outputS4%%outputS3%%outputS2%%outputS1%
pause>nul
exit /b

:: Function for the 4-bit Adder following the logic given
:_4bitAdder
set inputA1=%1
set inputA2=%2
set inputA3=%3
set inputA4=%4

set inputB1=%5
set inputB2=%6
set inputB3=%7
set inputB4=%8

set inputC=%9

call:_FullAdder %inputA1% %inputB1% %inputC%
set outputS1=%outputS%
set inputC=%outputC%

call:_FullAdder %inputA2% %inputB2% %inputC%
set outputS2=%outputS%
set inputC=%outputC%

call:_FullAdder %inputA3% %inputB3% %inputC%
set outputS3=%outputS%
set inputC=%outputC%

call:_FullAdder %inputA4% %inputB4% %inputC%
set outputS4=%outputS%
set inputC=%outputC%

:: In order return more than one number (of which is usually done via 'exit /b') we declare them while ending the local environment
endlocal && set "outputS1=%outputS1%" && set "outputS2=%outputS2%" && set "outputS3=%outputS3%" && set "outputS4=%outputS4%" && set "outputC=%inputC%"
exit /b

:: Function for the 1-bit Adder following the logic given
:_FullAdder
setlocal
set inputA=%1
set inputB=%2
set inputC1=%3

call:_halfAdder %inputA% %inputB%
set inputA1=%outputS%
set inputA2=%inputA1%
set inputC2=%outputC%

call:_HalfAdder %inputA1% %inputC1%
set outputS=%outputS%
set inputC1=%outputC%

call:_Or %inputC1% %inputC2%
set outputC=%errorlevel%

endlocal && set "outputS=%outputS%" && set "outputC=%outputC%"
exit /b

:: Function for the half-bit adder following the logic given
:_halfAdder
setlocal
set inputA1=%1
set inputA2=%inputA1%
set inputB1=%2
set inputB2=%inputB1%

call:_XOr %inputA1% %inputB2%
set outputS=%errorlevel%

call:_And %inputA2% %inputB2%
set outputC=%errorlevel%

endlocal && set "outputS=%outputS%" && set "outputC=%outputC%"
exit /b

:: Function for the XOR-gate following the logic given
:_XOr
setlocal
set inputA1=%1
set inputB1=%2

call:_Not %inputA1%
set inputA2=%errorlevel%

call:_Not %inputB1%
set inputB2=%errorlevel%

call:_And %inputA1% %inputB2%
set inputA=%errorlevel%

call:_And %inputA2% %inputB1%
set inputB=%errorlevel%

call:_Or %inputA% %inputB%
set outputA=%errorlevel%

:: As there is only one output, we can use 'exit /b {errorlevel}' to return a specified errorlevel
exit /b %outputA%

:: The basic 3 logic gates that every other funtion is composed of
:_Not
setlocal
if %1==0 exit /b 1
exit /b 0
:_Or
setlocal
if %1==1 exit /b 1
if %2==1 exit /b 1
exit /b 0
:_And
setlocal
if %1==1 if %2==1 exit /b 1
exit /b 0


(load "@lib/math.l")

(de fractalTree (Img X Y A D)
   (unless (=0 D)
      (let (R (*/ A pi 180.0)  DX (*/ (cos R) D 0.2)  DY (*/ (sin R) D 0.2))
         (brez Img X Y DX DY)
         (fractalTree Img (+ X DX) (+ Y DY) (+ A 30.0) (dec D))
         (fractalTree Img (+ X DX) (+ Y DY) (- A 30.0) (dec D)) ) ) )

(let Img (make (do 300 (link (need 400 0))))       # Create image 400 x 300
   (fractalTree Img 200 300 -90.0 10)              # Draw tree
   (out "img.pbm"                                  # Write to bitmap file
      (prinl "P1")
      (prinl 400 " " 300)
      (mapc prinl Img) ) )


To run:
Start up.
Clear the screen to the lightest blue color.
Pick a brownish color.
Put the screen's bottom minus 1/2 inch into the context's spot's y coord.
Draw a tree given 3 inches.
Refresh the screen.
Wait for the escape key.
Shut down.

To draw a tree given a size:
If the size is less than 1/32 inch, exit.
Put the size divided by 1/4 inch into the pen size.
If the size is less than 1/4 inch, pick a greenish color.
Remember where we are.
Stroke the size.
Turn left 1/16 of the way. Draw another tree given the size times 2/3. Turn right 1/16 of the way.
Turn right 1/16 of the way. Draw a third tree given the size times 2/3. Turn left 1/16 of the way.
Go back to where we were.


%!PS
%%BoundingBox: 0 0 300 300
%%EndComments
/origstate save def
/ld {load def} bind def
/m /moveto ld /g /setgray ld /t /translate ld
/r /rotate ld /l /lineto ld
/rl /rlineto ld /s /scale ld
%%EndProlog
/PerturbateAngle {} def
/PerturbateLength {} def
% ** To add perturbations, define properly PerturbateAngle and PerturbateLength, e.g.
% /PerturbateAngle {realtime 20 mod realtime 2 mod 1 eq {add} {sub} ifelse} def
% /PerturbateLength {realtime 10 mod 100 div realtime 2 mod 1 eq {add} {sub} ifelse} def
/fractree { % [INITLENGTH, SPLIT, SFACTOR, BRANCHES]
  dup 3 get 0 gt
  {
    0 0 m dup 0 get 0 exch l
    gsave
      dup 0 get 0 exch t
      dup 1 get PerturbateAngle r
      dup 2 get dup PerturbateLength s
      dup aload pop 1 sub 4 array astore fractree stroke
    grestore
    gsave
      dup 0 get 0 exch t
      dup 1 get neg PerturbateAngle r
      dup 2 get dup PerturbateLength s
      dup aload pop 1 sub 4 array astore fractree stroke
    grestore
  } if pop
} def
%
/BRANCHES 14 def
/INITLENGTH 50 def
/SPLIT 35 def
/SFACTOR .75 def
%
% BB check
%0 0 m 300 0 rl 0 300 rl -300 0 rl closepath stroke
%
0 g 150 0 t
[INITLENGTH SPLIT SFACTOR BRANCHES] fractree stroke
%
showpage origstate restore
%%EOF


#include <stdio.h>

typedef char pin_t;
#define IN const pin_t *
#define OUT pin_t *
#define PIN(X) pin_t _##X; pin_t *X = & _##X;
#define V(X) (*(X))

/* a NOT that does not soil the rest of the host of the single bit */
#define NOT(X) (~(X)&1)

/* a shortcut to "implement" a XOR using only NOT, AND and OR gates, as
   task requirements constrain */
#define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y)))

void halfadder(IN a, IN b, OUT s, OUT c)
{
  V(s) = XOR(V(a), V(b));
  V(c) = V(a) & V(b);
}

void fulladder(IN a, IN b, IN ic, OUT s, OUT oc)
{
  PIN(ps); PIN(pc); PIN(tc);

  halfadder(/*INPUT*/a, b, /*OUTPUT*/ps, pc);
  halfadder(/*INPUT*/ps, ic, /*OUTPUT*/s, tc);
  V(oc) = V(tc) | V(pc);
}

void fourbitsadder(IN a0, IN a1, IN a2, IN a3,
		   IN b0, IN b1, IN b2, IN b3,
		   OUT o0, OUT o1, OUT o2, OUT o3,
		   OUT overflow)
{
  PIN(zero); V(zero) = 0;
  PIN(tc0); PIN(tc1); PIN(tc2);

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

int main()
{
  PIN(a0); PIN(a1); PIN(a2); PIN(a3);
  PIN(b0); PIN(b1); PIN(b2); PIN(b3);
  PIN(s0); PIN(s1); PIN(s2); PIN(s3);
  PIN(overflow);

  V(a3) = 0; V(b3) = 1;
  V(a2) = 0; V(b2) = 1;
  V(a1) = 1; V(b1) = 1;
  V(a0) = 0; V(b0) = 0;

  fourbitsadder(a0, a1, a2, a3, /* INPUT */
		b0, b1, b2, b3,
		s0, s1, s2, s3, /* OUTPUT */
		overflow);

  printf("%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\n",
	 V(a3), V(a2), V(a1), V(a0),
	 V(b3), V(b2), V(b1), V(b0),
	 V(s3), V(s2), V(s1), V(s0),
	 V(overflow));

  return 0;
}


#include "colors.inc"
#include "transforms.inc"

#declare CamLoc = <0, 5, 0>;
#declare CamLook = <0,0,0>;
camera
{
  location CamLoc
  look_at CamLook
  rotate y*90
}

light_source
{
  CamLoc
  color White
}

#declare Init_Height    = 10;
#declare Spread_Ang     = 35;
#declare Branches       = 14;
#declare Scaling_Factor = 0.75;

#macro Stick(P0, P1)
  cylinder {
    P0, P1, 0.02
    texture { pigment { Green } }
  }
#end

#macro FractalTree(O, D, S, R, B)
  #if (B > 0)
    Stick(O, O+D*S)
    FractalTree(O+D*S, vtransform(D, transform{rotate y*R}),
      S*Scaling_Factor, R, B-1)
    FractalTree(O+D*S, vtransform(D, transform{rotate -y*R}),
      S*Scaling_Factor, R, B-1)
  #end
#end

union {
  FractalTree(<-2,0,0>, <1,0,0>, 1, Spread_Ang, Branches)
}


fractal :-
	new(D, window('Fractal')),
	send(D, size, size(800, 600)),
	drawTree(D, 400, 500, -90, 9),
	send(D, open).

drawTree(_D, _X, _Y, _Angle, 0).

drawTree(D, X1, Y1, Angle, Depth) :-
        X2 is X1 + cos(Angle * pi / 180.0) * Depth * 10.0,
        Y2 is Y1 + sin(Angle * pi / 180.0) * Depth * 10.0,
	new(Line, line(X1, Y1, X2, Y2, none)),
	send(D, display, Line),
	A1 is Angle - 30,
	A2 is Angle + 30,
	De is Depth - 1,
        drawTree(D, X2, Y2, A1, De),
        drawTree(D, X2, Y2, A2, De).


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RosettaCodeTasks.FourBitAdder
{
	public struct BitAdderOutput
	{
		public bool S { get; set; }
		public bool C { get; set; }
		public override string ToString ( )
		{
			return "S" + ( S ? "1" : "0" ) + "C" + ( C ? "1" : "0" );
		}
	}
	public struct Nibble
	{
		public bool _1 { get; set; }
		public bool _2 { get; set; }
		public bool _3 { get; set; }
		public bool _4 { get; set; }
		public override string ToString ( )
		{
			return ( _4 ? "1" : "0" )
				+ ( _3 ? "1" : "0" )
				+ ( _2 ? "1" : "0" )
				+ ( _1 ? "1" : "0" );
		}
	}
	public struct FourBitAdderOutput
	{
		public Nibble N { get; set; }
		public bool C { get; set; }
		public override string ToString ( )
		{
			return N.ToString ( ) + "c" + ( C ? "1" : "0" );
		}
	}

	public static class LogicGates
	{
		// Basic Gates
		public static bool Not ( bool A ) { return !A; }
		public static bool And ( bool A, bool B ) { return A && B; }
		public static bool Or ( bool A, bool B ) { return A || B; }

		// Composite Gates
		public static bool Xor ( bool A, bool B ) {	return Or ( And ( A, Not ( B ) ), ( And ( Not ( A ), B ) ) ); }
	}

	public static class ConstructiveBlocks
	{
		public static BitAdderOutput HalfAdder ( bool A, bool B )
		{
			return new BitAdderOutput ( ) { S = LogicGates.Xor ( A, B ), C = LogicGates.And ( A, B ) };
		}

		public static BitAdderOutput FullAdder ( bool A, bool B, bool CI )
		{
			BitAdderOutput HA1 = HalfAdder ( CI, A );
			BitAdderOutput HA2 = HalfAdder ( HA1.S, B );

			return new BitAdderOutput ( ) { S = HA2.S, C = LogicGates.Or ( HA1.C, HA2.C ) };
		}

		public static FourBitAdderOutput FourBitAdder ( Nibble A, Nibble B, bool CI )
		{

			BitAdderOutput FA1 = FullAdder ( A._1, B._1, CI );
			BitAdderOutput FA2 = FullAdder ( A._2, B._2, FA1.C );
			BitAdderOutput FA3 = FullAdder ( A._3, B._3, FA2.C );
			BitAdderOutput FA4 = FullAdder ( A._4, B._4, FA3.C );

			return new FourBitAdderOutput ( ) { N = new Nibble ( ) { _1 = FA1.S, _2 = FA2.S, _3 = FA3.S, _4 = FA4.S }, C = FA4.C };
		}

		public static void Test ( )
		{
			Console.WriteLine ( "Four Bit Adder" );

			for ( int i = 0; i < 256; i++ )
			{
				Nibble A = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };
				Nibble B = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false };
				if ( (i & 1) == 1)
				{
					A._1 = true;
				}
				if ( ( i & 2 ) == 2 )
				{
					A._2 = true;
				}
				if ( ( i & 4 ) == 4 )
				{
					A._3 = true;
				}
				if ( ( i & 8 ) == 8 )
				{
					A._4 = true;
				}
				if ( ( i & 16 ) == 16 )
				{
					B._1 = true;
				}
				if ( ( i & 32 ) == 32)
				{
					B._2 = true;
				}
				if ( ( i & 64 ) == 64 )
				{
					B._3 = true;
				}
				if ( ( i & 128 ) == 128 )
				{
					B._4 = true;
				}

				Console.WriteLine ( "{0} + {1} = {2}", A.ToString ( ), B.ToString ( ), FourBitAdder( A, B, false ).ToString ( ) );

			}

			Console.WriteLine ( );
		}

	}
}


#Spread_Ang     = 35
#Scaling_Factor = 0.75
#Deg_to_Rad = #PI / 180
#SizeH = 500
#SizeV = 375
#Init_Size = 100

Procedure drawTree(x1, y1, Size, theta, depth)
  Protected x2 = x1 + Cos(theta * #Deg_to_Rad) * Size, y2 = y1 + Sin(theta * #Deg_to_Rad) * Size
  LineXY(x1, y1, x2, y2, RGB(255, 255, 255))
  If depth <= 0
    ProcedureReturn
  EndIf
  ;draw left branch
  drawTree(x2, y2, Size * #Scaling_Factor, theta - #Spread_Ang, depth - 1)
  ;draw right branch
  drawTree(x2, y2, Size * #Scaling_Factor, theta + #Spread_Ang, depth - 1)
EndProcedure

OpenWindow(0, 0, 0, #SizeH, #SizeV, "Fractal Tree", #PB_Window_SystemMenu)
Define fractal = CreateImage(#PB_Any, #SizeH, #SizeV, 32)
ImageGadget(0, 0, 0, 0, 0, ImageID(fractal))

If StartDrawing(ImageOutput(fractal))
    drawTree(#SizeH / 2, #SizeV, #Init_Size, -90, 9)
  StopDrawing()
  SetGadgetState(0, ImageID(fractal))
EndIf

Repeat: Until WaitWindowEvent(10) = #PB_Event_CloseWindow


void setup() {
  size(600, 600);
  background(0);
  stroke(255);
  drawTree(300, 550, 9);
}

void drawTree(float x, float y, int depth) {
  float forkAngle = radians(20);
  float baseLen = 10.0;
  if (depth > 0) {
    pushMatrix();
    translate(x, y - baseLen * depth);
    line(0, baseLen * depth, 0, 0);
    rotate(forkAngle);
    drawTree(0, 0, depth - 1);
    rotate(2 * -forkAngle);
    drawTree(0, 0, depth - 1);
    popMatrix();
  }
}


(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)


import pygame, math

pygame.init()
window = pygame.display.set_mode((600, 600))
pygame.display.set_caption("Fractal Tree")
screen = pygame.display.get_surface()

def drawTree(x1, y1, angle, depth):
    fork_angle = 20
    base_len = 10.0
    if depth > 0:
        x2 = x1 + int(math.cos(math.radians(angle)) * depth * base_len)
        y2 = y1 + int(math.sin(math.radians(angle)) * depth * base_len)
        pygame.draw.line(screen, (255,255,255), (x1, y1), (x2, y2), 2)
        drawTree(x2, y2, angle - fork_angle, depth - 1)
        drawTree(x2, y2, angle + fork_angle, depth - 1)

def input(event):
    if event.type == pygame.QUIT:
        exit(0)

drawTree(300, 550, -90, 9)
pygame.display.flip()
while True:
    input(pygame.event.wait())