52
Other Languages • We wrap up our examination of programming languages by briefly considering a wide variety – we will look at some • meaningfully important historic languages of note – apl to demonstrate an array-based language – a stack-based language (because some of the bizarre languages use this approach) – bcpl to see more of how C-languages evolved – some truly abnormal languages • a couple of the newer languages of note • bizarre languages – esoteric languages » languages that were developed for fun, or as a proof of concept, but not meant to be taken as serious languages – obfuscated languages » languages that are purposefully very difficult to understand and use

Other Languages

  • Upload
    ronli

  • View
    31

  • Download
    0

Embed Size (px)

DESCRIPTION

Other Languages. We wrap up our examination of programming languages by briefly considering a wide variety we will look at some meaningfully important historic languages of note apl to demonstrate an array-based language - PowerPoint PPT Presentation

Citation preview

Page 1: Other Languages

Other Languages• We wrap up our examination of programming

languages by briefly considering a wide variety– we will look at some

• meaningfully important historic languages of note– apl to demonstrate an array-based language– a stack-based language (because some of the bizarre languages use

this approach)– bcpl to see more of how C-languages evolved– some truly abnormal languages

• a couple of the newer languages of note• bizarre languages

– esoteric languages» languages that were developed for fun, or as a proof of concept,

but not meant to be taken as serious languages– obfuscated languages

» languages that are purposefully very difficult to understand and use

Page 2: Other Languages

APL• APL – a programming language (literally)

– developed in the 1960s– meant to be a language to express mathematical ideas– notation consists of a set of symbols and a syntax to describe

the processing of data. – APL has primitive instructions that can manipulate n-

dimensional arrays of data simplifying a program• these primitives can be strung together in a single line of code as a

combination of array manipulations

– APL is interactive (interpreted) – useful for rapid prototyping– APL is one of the most concise, consistent, and powerful

programming languages ever devised (according to the author of a website I got this info from)

Page 3: Other Languages

APL Operations• APL programs are typical 1/5

to 1/20 the size of other programs due to the built-in array and math operations– sort up (or down) a set of

numbers – raise any number to any power – take any root of a number – logarithms and exponentials – examine separately the integer

and decimal parts of a number – convert number bases – trigonometric functions – random numbers – rearrange arrays of numbers into

different size and shape arrays, i.e. vectors, matrices, and multi-dimensional "cubes".

DIMENSION X(100),Y(100) READ(5,10) N,(X(I),I=1,N)10 FORMAT (15/(F10.2)) DO 20 I=1,N A=X(I) L=1 DO 15 J=1,N IF(A-X(J))15,15,1212 A=X(j) L=J15 CONTINUE Y(I)=A20 X(L)=100000. WRITE(6,30) (Y(I),I=1,N)30 FORMAT(E15.2) END

APL Arraysorting program

FORTRANArray sorting program

Page 4: Other Languages

Sample APL• A 15 23 8 19 21 6

– This creates an array, A with the values as specified• B 2 4 1 2 3 4 5 6 7 8

– This creates a 2x4 array with 1..4 being in the first row and 5..8 being in the second row (is the Greek letter rho

• Once you create arrays, here are some operations to perform on them– +/A Computes the sum of the array elements (returns 92

in this case)– A + 1 Adds 1 to each element of array A– x/A Computes the product of the array elements– B Returns the dimensions of the array (in this case, 2 4)– (+/A)A Computes the sum over the size of the array

(average)This final one computes and displays all ofthe prime numbers ending at 20See http://www.users.cloud9.net/~bradmcc/APL.htmlfor an explanation (halfway down this page)

Page 5: Other Languages

BCPL• Basic Combined Programming Language, the precursor of

C (also B)– block structured like Algol and syntactically somewhat similar to

Algol but it introduced the { } for blocks (although since many early keyboards lacked these characters, $( and $) was also used, and

• was typeless• had only 1-D arrays• was case insensitive for identifiers but all reserved words start with upper

case letters• had all of C’s control structures but included an Unless-Do and Repeat-

Until (which would later be found in Pascal/Modula)• loop (infinite loop)• more primitive for loop• test-then-else rather than if-then-else

– introduced pass-by-value as the only form of parameter passing, but also had global memory (a 1-D array to store any global values) for variables that should be changed in a subroutine

– had both functions and procedures

Page 6: Other Languages

BCPL Examples

GET "LIBHDR" LET START ( ) BE { LET F(N) = N=0 -> 1, N*F(N-1) FOR I = 1 TO 10 DO WRITEF("F(%N), = %N*N", I, F(I)) FINISH }

GET "LIBHDR"MANIFEST { BOTTLES = 99}

LET START( ) BE { LET BEERS(N, S) BE { TEST N = 0 THEN WRITEF("No more bottles") ELSE WRITEF("%N bottle%S", N, (N = 1) -> "", "s") WRITEF(" of beer%S", S) }

FOR I = BOTTLES TO 1 BY -1 DO { BEERS(I, " on the wall, ") BEERS(I, ".*NTake one down, pass it around.*N") BEERS(I - 1, " on the wall.*N") } FINISH}

Manifest – declares constantsLet – declares functions, procs

GET "LIBHDR" LET START() = VALOF { LET LC, WC, CC = 0, 0, 0 AND SP = TRUE { LET CH = RDCH( ) IF CH=ENDSTREAMCH BREAK IF CH='*N' THEN LC := LC + 1 TEST CH='*T' | CH='*N' | CH='*S'

THEN SP := TRUE OR IF SP { WC := WC + 1 SP := FALSE } CC := CC + 1 } REPEAT WRITEF("%N %N %N*N", LC, WC, CC) RESULTIS 0 }

Page 7: Other Languages

Forth• An extensible stack-based language from the 1970s

– Interpreted language– All commands are part of a dictionary

• defining your own commands adds to the current dictionary (because its interpreted, you can continue to add during the current session)

– All data interact with a built-in data stack• this will require that operations be specified in a postfix notation• example: 5 4 + .

– pushes 5, then 4, + pops 5 and 4, adds them, pushes 9 onto the stack, . ends the instruction, 9 popped off the stack and returned

– Built-in stack operations:• DUP – duplicates the top of the stack• SWAP – swaps the top 2 elements• DROP – drops the top element of stack• ROT – Rotate the top 3 numbers

Page 8: Other Languages

Variables and Words• To define a variable use variable name

– this allocates storage for the integer variable name in the dictionary

• When you use the variable name, the address of the variable is placed on the stack– ! stores stack values into a variable as in

• variable year• 2005 year !

– @ fetches variable and places it on the stack• year @ .

– Arrays and strings are also available where the index precedes the variable name as in 10 array !

• To define a dictionary entry (word): :name body;– This adds to the dictionary a new routine whose name is

name and whose body consists of all characters after the space following name and prior to the ;

– For example, :square dup *; defines square as a routine that will duplicate the top of the stack and then multiply the top two elements on the top of stack

• You would execute square by doing variable square . And this would compute variable2 and return that value

Page 9: Other Languages

Control Statements• Conditional operators pop the top two values off the stack,

perform the comparison and push -1 (true) or 0 (false) onto the stack

• A control statement can then use the result• If statements:

– If operator statement(s) then ;• If < @ x * ! then ;

– This means “if top item on stack < second item” then retrieve x and multiply it by top of stack (which is now -1) and push to top of stack – in effect, this does “if top < second x = x * -1”

– If operator statement(s) then statement(s) else ;• Loop statements:

– Limit Init do var statement(s) loop ;• As in 10 0 do i . loop ; -- which prints 0..9

– There is also an until and while repeat• begin statement(s) condition until .• begin condition while statement(s) repeat .

Page 10: Other Languages

SNOBOL• SNOBOL (String-oriented Symbolic Language) dates back to 1962

but its standard version, SNOBOL 4 was implemented in 67• The language contains the following features

– string manipulation operations - has several of these operations which allow a string to be tested for contents and make replacements in the string

– pattern matching- involves examining substrings, for the occurrences of specified substrings

– dynamically typed - no type declarations, variables may take on any type at any time

• aside from the basic data types, SNOBOL allowed user defined structures like Simula 67 or Algol 68

– interpreted language with a compiler

• SNOBOL statements are of the form– label statement :(label) -- the :(…) is a goto statement after this instruction

executes and is optional like the label that precedes the statement– statements have varying syntax and can look like message passing or

imperative statements

Page 11: Other Languages

Sample SNOBOL Program&TRIM = 1WORDPAT = BREAK(&LCASE &UCASE) SPAN(&LCASE &UCASE "'-") .

WORDCOUNT = ARRAY('3:9',0)

READ LINE = INPUT :F(DONE)NEXTW LINE WORDPAT = :F(READ)

COUNT<SIZE(WORD)> = COUNT<SIZE(WORD)>+ 1 :(NEXTW)DONE OUTPUT= "WORD LENGTH NUMBER OF OCCURRENCES"

I = 2PRINT I = I + 1

OUTPUT= LPAD(I,5) LPAD(COUNT<I>,20) :S(PRINT)END

This program inputs a text file and reads each word and counts the numberof 3-letter, 4-letter, …, 9-letter words and reports on the number of each found

Page 12: Other Languages

JCL• Job Control Language– IBM Mainframe language to control execution of programs– JCL instructions are thought of as cards (since originally each instruction

was on its own punch card)– instructions specify

• to submit a job to the operating system • to request a resource for the job (input file, output file, printer, etc)• to control the system’s processing of the job

– instructions include:• job statement – specifies job name, accounting and billing information, and

supplies options to control processing of the job• execute statement– instructions the computer which program or procedure to

execute• data definition statement – identifies data sets that will be used or created by the

job• comment statement– contains comments• delimiter/null statement – signifies end of a job step or end of job• procedure/procedure end statement – marks the beginning/end of a procedure

and assigns default values to parameters• control/end control statement – marks the beginning/end of a program control

statement• output JCL statement – specifies the processing options that the job entry

subsystem uses to print a sysout data set

Page 13: Other Languages

JCL Examples

//SQADB512 DD DSN=SIMOTIME.DATA.SQADB512,DISP=(NEW,CATLG,DELETE), // STORCLAS=MFI, // SPACE=(TRK,5), // DCB=(RECFM=FB,LRECL=512,BLKSIZE=5120,DSORG=PS)

//PDSCRTP3 PROC//PDSCRTS1 EXEC PGM=IEFBR14//TEMPLIB1 DD DISP=(NEW,CATLG),DSN=&DSNAME,// STORCLAS=MFI,// SPACE=(TRK,(45,15,50)),// DCB=(RECFM=FB,LRECL=80,BLKSIZE=800,DSORG=PO)// PEND

//SIMOJOB1 JOB (ACCTINFO),CLASS=A,MSGCLASS=C,NOTIFY=USERID//JOBLIB DD DSN=SIMOTIME.DEVL.LOADLIB1,DISP=SHR//*//STEP0100 EXEC PGM=PROGRAM1//*//STEP0200 EXEC PGM=PROGRAM2//*//STEP0300 EXEC PGM=PROGRAM3//STEPLIB DD DSN=SIMOTIME.DEVL.TEMPLIB1,DISP=SHR//*//STEP0400 EXEC PGM=PROGRAM4

Page 14: Other Languages

Mathematica• This is a language for performing mathematical

calculations and plotting of mathematical functions– Mathematica is both a tool and a programming language, it

includes features similar to other languages that we have studied

• Lisp – list manipulation• Perl, Prolog – pattern matching on symbolic data• APL – structured data manipulation• C++ & Smalltalk – OO• Pascal/C – procedural programming using modules• FORTRAN/C – contains a number of built-in mathematical functions

– as a tool, the language has • an interpreted interface for session work, much like Lisp, Python,

Ruby, • a 2D and 3D data visualizer to plot mathematical functions• built-in solvers for systems of equations, differential equations,

recurrence relations• multi-variate statistics libraries and other features

Page 15: Other Languages

Some ExamplesIn[2]:= FindRoot[Exp[x] == x^2 + 2, {x, -1}] Out[2]= {x -> 1.3190736768573652}

In[6]:= l1 = {}; (* initialize as empty list, since we want a list in the end *) Do[l2 = {}; Do[l2 = Append[l2, GCD[i, j]], {j, 1, 5}]; l1 = Append[l1, l2], {i, 1, 5}]

Integrate[ a x^2 + b x + c ,{x,0,1}] -- integration example

Clear[uRandomVector,a] uRandomVector[size_,{min_,max_}]:=Table[Random[Integer,{min,max}],{size}]a=uRandomVector[4,{0,1}];Clear[i,x,y,cnt,ls] cnt=0; ls={}; i=1; While[(i<=Length[a]),x=a[[i]];       While[((i<=Length[a])&&(a[[i]]==x)),cnt+=1;i+=1];       ls=Append[ls,cnt];       cnt=0]

Page 16: Other Languages

Mouse• A language originally intended for microcomputers

with a small amount of memory, interpreted and stack-based, using postfix notation– the unique aspect of Mouse is that the program is specified

as a single stream of symbols so that a program will tend to be very short (in terms of byte length)

– variables are single characters and commands are also typically single characters

• Mouse includes conditional branches, loops, pointers, macros, arrays and code tracing

• Rather than displaying the entire table of symbols for commands, here are some brief examples:

X. Y: assign X to Y N. 1 + N: increment N by 1 P. Q. P: Q: swap values of P and Q ? A: input a number and store in A P. ! print variable P

1 N: N = 1( N. N. * ! “ ” Print N * N N. 10 – 0 < ^ If N < 10 – 0 then exit N. 1 + N: N = N + 1$ End Program

Page 17: Other Languages

Groovy• This is a new language, an extension to Java

– It includes these features• == compares data (whether primitive or the values that make up

an object) and not references, so for instance if a and b are Strings, a == b compares the two Strings’ values

• the ; is not needed unless multiple statements are on the same line – the interpreter is able to judge the end of an instruction if it ends with a \n

• supports operator overloading like C++• includes the tuple type from Python (indexed via arrays) as in list

= [“hello”, 5, 3.14] and then list[2] is 3.14• functions can be passed as parameters, like in C++• uses the Java for loop but also has a simpler counting loop as in

Python: for(i in 1..10)• closures have built-in iterator operations• as with Ruby, automatically generated mutators and accessors for

all private data members

Page 18: Other Languages

Lua• Lua is a dynamically typed scripting language

– Lua is a very small language that is very extendable– While not overtly OO (for instance, no built-in support for

inheritance)• it can be expanded to include inheritance to make it OO and to

handle AOP• the language also fits the imperative paradigm by having control

statements (similar to Modula/Pascal) • the functional paradigm borrowing other aspects from Scheme• and concurrent programming

– The basic unit of storage is known as a table, which is a heterogeneous associative array

• aside from associative arrays, Lua provides local and global (the default) variables with types that include numbers, strings, and booleans

• traditional arrays, sets, records and lists are implemented using tables

Page 19: Other Languages

First Class Functions• Lua supports first class functions (functions that

can be passed as parameters) but also allows – functions to be pointed to and

– functions to be redefined

• For instance, you can do the following in order to “save” a function while re-implementing it:

do local oldprint = print // save the old function function print(s) // redefine the function if s ==“foo” then

oldprint(“bar”) // cal the old function else oldprint(s) end endend

Page 20: Other Languages

Metatables• One of Lua’s greatest strengths is the inclusion of

metatables and the ability for the programmer to modify metatables– A metatable is attached to every variable that contains data

describing the variable including how the variable should be treated under various conditions

– To add or alter a metatable entry, use name.__entry = where name is the name of the variable and entry is the metatable element

• We can then use the metatable entry in situations where the variable might not normally be usable– For instance, if a variable x is not a string but we still want to

know its length, we can obtain it by doing• metatable(x).__len

– Hopefully the len metatable entry is present to either return x’s length or compute x’s length

– Built in metatable entries exist for a number of useful features such as length, index, concat and eq

Page 21: Other Languages

Go• A systems programming language from Google

that combines features of C/C++ and Python– For instance, the semicolon is only used to separate

elements in the for loop– There is a built-in string type where strings are

immutable but not objects– Assignment copies contents of values, not references

(pointers) unless you explicitly request the address– Go is strongly typed

• Go supports OOP, functional programming (functions are first class objects), concurrent programming and procedural programming– The language supports the development of ontologies

(as used for the semantic web)

Page 22: Other Languages

Example Code

main .. { include "sys:go/io.gof". include "sys:go/stdlib.gof". main() ->

drink(99); stdout.outLine("Time to buy some more beer...").

drink(0) -> {}. drink(i) -> stdout.outLine( bottles(i) <> " on the wall,\n" <> bottles(i) <> ".\n" <> "take one down, pass it around,\n" <> bottles(i) <> " on the wall.\n"); drink(i-1).

bottles(0) => "no bottles of beer". bottles(1) => "1 bottle of beer". bottles(i) => i^0 <> " bottles of beer". }

func sum(a []int) int { s := 0 for i := 0; i < len(a); i++ { s += a[i] } return s }

func Open(name string, mode int, perm int) (file *File, err os.Error) { r, e := syscall.Open(name, mode, perm) if e != 0 { err = os.Errno(e) } return newFile(r, name), err }

Page 23: Other Languages

Obfuscated/Esoteric Languages• The idea behind these languages is to either (or

both)– Hide the meaning of the instructions, that is, to make

programming as challenging as possible– Make languages as simple as possible by reducing the

number of operators/operations to a minimum and permit a very small compiler

• I’m going to break these down into roughly three categories:– Spatial languages – languages whose instructions

pertain to physical locations among the data– Stack languages – languages like Forth where the data

are implied to be on one or more stacks– Other – languages that are just plain weird

Page 24: Other Languages

False• One of the first obfuscated languages, it uses postfix

notation for operations like Lisp uses prefix notation– operators include _ for unary minus, =~ for not equal and ~ for

not• for instance, a;1_=~ means a <> -1 and a;0>a;99>~& means a>0 and

a<99– data types are limited to integer and character, which are single

quoted like Lisp (e.g., ’a)• variable names are limited to single letters• assignment is :• ; is used to dereference a variable • example: 1a: is a = 1; and a;1+b: is b = a + 1;

– False uses an implied stack (all operations are via stack, that’s why the language uses postfix)

– functions are defined as lambda functions (unnamed) and placed inside of [ ] where parameters are taken from the stack based on the number of values that precede the function call

• you can declare a function’s name by placing name: after the function definition

Page 25: Other Languages

False Instructions• Built-in stack operations include $ to duplicate top of stack, %

to delete top of stack, \ to swap top two of stack, @ to rotate top 3 of stack

• The only control instruction are – if which is denoted using ? after the then or else clause, for instance:

• a;1=[“hello”]?– if a = 1 then print “hello”

• a;0>[1:b]?a;0=[0:b]?~[-1:b]?– if a > 0 then b = 1 else if a = 0 then b = 0 else b = -1

– while loop which is denoted with a # after two lambda functions, the condition and the body

• [a;1=][2f;!]# – while (a = 1) f(2)

• [a;0>][a;a-b:b;b-1:]#– while(a>0) { a = a – b; b = b – 1;}

– output is simply [“literal”] or [var] or [.] (print top of stack as number) or [,] (print top of stack as char)

– input follows the ^ symbol which means “stdin”

Page 26: Other Languages

False Examples2[1+]! – [1+]

is a function that adds 1 to the argument passed, so this code returns 3

[1+]i: defines the function as i, and can be called as valuei! as in 2i! which returns 3

[^$1_=~][,]# while((c=getchar( )) != -1) putc(c); more literally, push the char on top of stack and then pop

it off and print it

[$1=$[\%1\]?~[$1-f;!*]?]f:this defines a function f as follows:f(x) = if(top of stack = 1) then return 1 else return f(x – 1)

Page 27: Other Languages

Brainf*ck• Goal: create a language with the smallest compiler ever

– Brainf*ck’s original compiler was 240 bytes!• supposedly a newer compiler is under 200 bytes

– The language manipulates an array of 30,000 bytes with a single pointer

• instructions move the pointer or manipulate what is being pointed at• instructions (C equivalents given, assume p is pointer):

– > is ++p– < is --p– + is ++*p– - is --*p– . is putchar(*p)– , is *p = getchar( )– [ is while(*p) { that is, while loop while pointer *p = = 0– ] is }, that is, ends the while loop started with [

Page 28: Other Languages

BF Examples

This program multiplies the original input value by 10and stores the value back into the array

[>+<-]> ; move num one right ie num2=num>>++++++++++ ; load 10 into fourth element[ <<[<+>>+<-] ; add num2 to first and third element >[<+>-]> ; num2=third element - ; loop ten times]<<[-]< ; clear num2#

BF Hello World program (creates the integer values for ASCII “Hello World”and outputs these values)

++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.

Input text and output itbackwards:

>.+[>.+]<[-.<]

Program to compute 4 + 3 and output the result:,>++++++[<-------->-],,[<+>-],<.>.

Page 29: Other Languages

Argh!• BF/Esoteric language where commands are single letters

and control is based on orientation of commands in a 2D grid

– Execution starts with j at position 0, 0• j indicates “go down 1 position”• l means “process commands to the right”• p and P are print commands to print the character below or above the

letter• q means quit (end of program)

– Programs are limited to a 80x40 grid of Ascii characters• Aargh! is an extension to Argh! where programs can be Nx40 where

there is no restriction on N (that is, programs can have an unlimited length but no more than 40 columns)

j world lppppppPPPPPPq hello,

Note: the type is not lined up exactly, eachletter of “world” and “hello” shouold appeardirectly above or below a p/P

Page 30: Other Languages

Argh Commandsh, j, k, l - set execution direction to "left", "down", "up", "right"H, J, K, L - move instruction pointer left/down/up/right to the next cell whose

value matches the value on top of the stack, set execution direction to "left", "down", "up", "right"

x/X - if value on top of the stack is positive, turn the execution direction 90 degrees to the right/left

q - quit: end program executions/S - store (push) value of the cell below/above the current cell to stackd/D – duplicate/delete top value on stacka/A - add value of cell below/above current cell to the value on top of the stackr/R - reduce the value on top of the stack by the value of the cell below/abovef/F - fetch (pop) value from top of stack and store to cell below/abovep/P - send value below/above the current cell to stdoutg/G - get one byte from stdin and store in cell below/abovee/E - insert value of system EOF in cell below/above

Argh! and Aargh! allow self-modifying code – instructions canbe used to overwrite instructions!

Page 31: Other Languages

Kipple• A BF/esoteric language

– the goal is minimalism – a language with very few commands– the language is based on stack storage

• 26 built-in stacks available, called a-z, i and o are reserved for pre-execution input and post-execution output only, no other variables

– commands are limited to• pushing/popping off of stacks

– 5 > a – pushes 5 onto stack a, a > b pops the top of stack a and pushes the item onto b, a < b does the same

• adding/subtracting two stack items or one stack item and one numeric operand – a + 5 pushes (top of a + 5) onto a, a + b pushes (top of a + top of b) onto a, a + 5

pushes 5 onto a if a is empty

• clearing a stack (if the top of stack stores 0)– a? pops all elements off of a if the top of a is 0

• a loop that iterates through the body until a given stack is empty– (a instructions) repeats the instructions, one time per element of a until a is empty

• strings are converted into individual ascii values and pushed/popped as ints– “abc” > a pushes 97, 98 and 99 onto a in order (so that the top of stack a is 99)– @value > o pushes the value onto the output stack, not its ascii character

Page 32: Other Languages

Kipple Example 1# Prints the lyrics to the famous "99 bottles of beer" song

99>n # push 99 onto stack n

(n # while n is not empty 10>s # 10 is ascii for “new line”, push new line onto s n+0 n>@ (@>t) (t>s) s<" bottle" n-1 n>a? (a "s">s 0>a?) s<" of beer on the wall" 10>s

# output 1 line of this verse to stack s n+0 n>@ (@>t) (t>s) s<" bottle" n-1 n>a? (a "s">s 0>a?) s<" of beer"

# output 1 line of this verse to stack s n-1 10>s<"Take one down and pass it around" 10>s

# compute next n (n-1) and output next line of verse with new n n+0 n>@ (@>t) (t>s) s<" bottle" n-1 n>a? (a "s">s 0>a?) s<" of beer on the wall" 10>s

# output last line of this verse to stack s n? # clear stack n if top of stack is 0, that is, we have reached the) # end of the song, and therefore empty stack exits the loop

(s>o) # take everything in s and move it to o (output stack)

Page 33: Other Languages

More Kipple Examples# Prints the 25 first Fibonacci numbers

24>n0>t 1>a

# push fibonacci numbers onto stack t(n-1 a+0 t<a>b+a c<b>a<c n? )

# output numbers:(t>@ (@>o) 32>o)

# Bubblesort by DeathPing

(i d+1 (b>c 0>b? x?) (x? d+0 d>f) ) (c>i) )0>d? (f>o)

# Reverse(i>r)(r>o)

# Unix cat(i>o)

Page 34: Other Languages

Chef• Like Kipple, Chef is another stack-based programming

language– programs in Chef are natural language statements that are

supposed to be recipes– the natural language-based instructions are converted into

stack commands based on the following• ingredients represent integer or character values for data

– dry ingredients are interpreted as numeric values and liquid ingredients are interpreted as characters (they are stored as int ASCII values so the interpretation is important to output the right value)

– dry vs. liquid is based on the measurement used (e.g., g, kg are dry and ml, l are liquid)

– ingredients themselves are merely symbols and so can be anything the programmer desires

• recipe steps represent stack operations– see the next slide

• recipe references to mixing bowls and baking dishes represent different stacks to manipulate

• other information, which is optional, is merely decorative such as baking time, oven temperature, and the final statement is how many people the recipe serves (required, but does nothing in the program)

Page 35: Other Languages

Chef Operations• Take ingredient from refrigerator. – input statement• Put ingredient into [nth] mixing bowl. – pushes onto stack n• Fold ingredient into [nth] mixing bowl. – pops off stack n and

places it into variable ingredient• Add ingredient [to [nth] mixing bowl].– performs top of stack n +

ingredient and pushes onto stack n• Remove ingredient [from [nth] mixing bowl]. – same but does

subtraction• Combine ingredient [into [nth] mixing bowl].– same but multiplies• Divide ingredient [into [nth] mixing bowl].– same but divides• Add dry ingredients [to [nth] mixing bowl]. – adds all dry

ingredients and pushes onto stack n• Liquefy | Liquify ingredient. – converts from int to char• Liquefy | Liquify contents of the [nth] mixing bowl. – same for top

of stack n

Page 36: Other Languages

Continued• Stir [the [nth] mixing bowl] for number minutes. – rotates

number of elements on stack n • Mix [the [nth] mixing bowl] well. – randomizes order of items

on stack n• Clean [nth] mixing bowl. – removes all elements from stack n• Pour contents of the [nth] mixing bowl into the [pth] baking

dish. – copies all elements of stack n onto stack p• Verb the ingredient. – this is followed by another statement

and executes the next statement based on the numeric value stored in ingredient (a for loop), where the number of ingredient is decremented each time throughVerb [the ingredient] until verbed. – ends the loop. The verb used is arbitrary.

• Serve with auxiliary-recipe. – this invokes the subroutine auxiliary recipe.

• Refrigerate [for number hours]. – exits the recipe or auxiliary recipe, printing out the number of baking dishes used in the recipe if the recipe contains a number of hours (cooking time)

Page 37: Other Languages

Example: Compute FibonacciFibonacci Numbers with Caramel Sauce.

Ingredients.100 g flour250 g butter1 egg

Method.Sift the flour. Put flour into mixing bowl. Serve with caramel sauce. Stir for 2 minutes. Remove egg. Rub the flour until sifted. Stir for 2 minutes. Fold the butter into the mixing bowl. Pour contents of the mixing bowl into the baking dish.

Serves 1.

Page 38: Other Languages

ContinuedCaramel Sauce.

Ingredients.1 cup white sugar1 cup brown sugar1 vanilla bean

Method.Fold white sugar into mixing bowl. Put white sugar into mixing bowl. Fold brown sugar into mixing bowl. Clean mixing bowl. Put white sugar into mixing bowl. Remove vanilla bean. Fold white sugar into mixing bowl. Melt white sugar. Put vanilla bean into mixing bowl. Refrigerate. Heat white sugar until melted. Put white sugar into mixing bowl. Remove vanilla bean. Fold white sugar into mixing bowl. Caramelise white sugar. Put vanilla bean into mixing bowl. Refrigerate. Cook white sugar until caramelised. Put white sugar into mixing bowl. Serve with caramel sauce. Fold brown sugar into mixing bowl. Put white sugar into mixing bowl. Add vanilla bean. Serve with caramel sauce. Add brown sugar.

Page 39: Other Languages

Shakespeare• Like Chef but the instructions are coded as if you

are writing a play with characters (variables) and scenes (subroutines)– The reserved words in this case are based on whether a

word is a verb or noun or adjective or a character in the play

– Characters are declared at the top of the play in a Dramatis Personae section

• each character represents its own stack• The declaration is charactername, description (description is

ignored)

– Characters enter into dialog with each other – the dialog manipulates one or more stacks through push, pop, topmost operations, conditions, and arithmetic operations

Page 40: Other Languages

Continued• Acts and scenes

– Each program is broken into procedural units known as acts and scenes

• Each act and scene is given a roman numeral identifier, these are used as GOTO statement labels

• Act I: Hamlet’s last battle (the text after the : is a comment)– Characters must explicitly enter and exit an act

• At most, only two characters can be on stage at a time• The exeunt statement calls all listed characters to leave at the

same time– [Enter Juliet]– [Enter Romeo and Juliet]– Exeunt Romeo and Juliet]

– Scenes will consist of lines of dialog• Lines are the commands and fall into three categories

– Control statements (see the next slide)– I/O statements, which are prefaced with the expression “Open your

heart” (input) or “Speak your mind” (output)– Assignment statements (see the next slide)

Page 41: Other Languages

Dialog/Instructions• Numbers (literals) are represented using two

combining schemes– A noun is equal to 1, any adjective that precedes it

doubles the value, so for instance, 3 adjectives and a noun is 8

– You can combine numbers with such phrases as “the sum of … and …” or “the difference between … and …”

• “The difference between a small, tired, dirty pony and a big boy is nothing”: this represents 8 – 2 = 6

– Assignment statements are dialog between one or two characters and the direction of the assignment (which character) is based on whether the dialog uses first person or second person

– The dialog “Remember me” means to push the latest value on to that character’s stack whereas “Recall …” means to pop the latest value from the stack

Page 42: Other Languages

Control Statements• There are two forms of control statements:

– Go to statements specify particular scenes as is “Let us return to scene III”

– Selection statements are broken into a question (condition) and actions, possibly spoken by multiple characters

• Questions ask “is X as good as Y” or “is X better than Y” or “is X worse than Y”

– example: Am I as horrid as a flirt-gill? This compares the value of the current speaker (their stack’s top value) against a literal computed by “flirt-gill”

• The action may be a go to statement, assignment statement or input or output

• Notice that there is no loop, you must construct loops as you would in assembly language, by combining selection statements and go to statements

Page 43: Other Languages

Example: Reversing an Input StringOthello, a stacky man. Lady Macbeth, who pushes him around till he pops.

Act I: The one and only. Scene I: In the beginning, there was nothing. [Enter Othello and Lady Macbeth] Othello: You are nothing!

Scene II: Pushing to the very end. Lady Macbeth: Open your mind! Remember yourself. Othello: You are as hard as the sum of yourself and a stone wall.

Am I as horrid as a flirt-gill? Lady Macbeth: If not, let us return to scene II. Recall your imminent death! Othello: You are as small as the difference between yourself and a hair!

Scene III: Once you pop, you can't stop! Lady Macbeth: Recall your unhappy childhood. Speak your mind! Othello: You are as vile as the sum of yourself and a toad! Are you better than nothing? Lady Macbeth: If so, let us return to scene III. Scene IV: The end. [Exeunt]

Page 44: Other Languages

4DL• Another stack-based language, but here, the operators manipulate

either the top of stack, or locations of a 4-D array– all operations are single ascii characters– the instruction pointer (program counter) moves not sequentially but based

on the direction that the instruction steers it (much like the change of directions available in Argh!)

– so the current instruction is at some location (i, j, k, l) in the 4-D array and the instruction might cause us to go to i++, i--, j++, j--, k++, k--, l++ or l--

• Instructions are to – push items adjacent to the current instruction pointer location (for instance,

push i+ means take the character at (i+1, j, k, l) and push it onto the stack)– add or subtract top two items of the stack– pop off stack and if not zero, skip the next coordinate in the current

direction– skip the next character in the program– change directions in 4-space (change the dimension being incremented or

decremented, or change from incr to decr)– input to stack, output from stack

Page 45: Other Languages

ExampleHello World program Shows control flow

P – push X+, p push X-, B – push Y+, b – push Y-, D – push Z+, d – push Z-, Q – push T+, q – push T-, X/x – change to X+ or X- direction (similarly for Y/y/Z/z/T/t), , - input to stack, ? – pop and if not zero then skip instr, % - end, 0 – push 0 to stack, . – pop and print

Page 46: Other Languages

Unlambda• A real BF language

– the goal is to make a functional language without using lambda functions to define anything

• this means no variables and no parameters!– Unlambda has no

• tape/array/stack (making it unlike other languages that are based on the Turing machine)

• local variables or integer processing• control constructs (loops, selection statements)

– literally everything in Unlambda is a function call based on 7 primitive functions and the application operator (like Lisp’s eval)

• ` – apply function to function• k – evaluate two functions returning the result of the first function• s – apply first function to third function, second function to third function,

and result of first function call to result of second function call• i – return argument without evaluation• `kFG = F• ``sFGH = ``FH`GH• .x – outputs x and returns x• Other built-in functions are d, c, v, these are much harder to explain so we

won’t go over them

Page 47: Other Languages

Programming Unlambda• The basic idea is to write your program as lambda

functions • And then use abstraction elimination to convert your

lambda function into unlambda– for instance, lambda# (x) F (where F is the code for your

function) is rewritten as ``si`FF

• Loops are only available through tail recursion• Numbers are represented in one of a couple of ways

– side effects generated by a function– by using .* to represent 1 and then nested applications of

this• 1 is ``s`kski.* and 2 is ``s``s`kski.* and 3 is ``s``s`ksk``s``s`kski

Page 48: Other Languages

Sample Unlambda CodeHello world program```s``sii`ki ``s``s`ks ``s``s`ks``s`k`s`kr ``s`k`si``s`k`s`k `d````````````.H.e.l.l.o.,. .w.o.r.l.d.! k k `k``s``s`ksk`k.*

Print out Fibonacci sequence```s``s``sii`ki `k.*``s``s`ks ``s`k`s`ks``s``s`ks``s`k`s`kr``s`k`sikk `k``s`ksk

# Print integers consecutively (each integer n is printed as a line of n asterisks)````s``s`ks``s`k`si``s`kk``s`k `s``s`ksk # Increment ``s`k ``s``s``si`k.*`kri # Print n (and return n) i`ki `ki # The number zero (replace by i to start from one) ``s``s`ks``s`k`si``s`kk``s`k # Ditto (other half-loop) `s``s`ksk ``s`k ``s``s``si`k.*`kri i`ki

Page 49: Other Languages

Whitespace• Most languages (and compilers) ignore white space

(blanks, tabs, return keys) but Whitespace is a language that uses only these keystrokes as meaningful elements– Whitespace uses a stack and a heap for storage and has basic

I/O and arithmetic operations, push and pop, pointers, labels for branches, conditional and unconditional branches, and subroutines

– definitely an obfuscated language– arithmetic operations and the stack only operate on integers

(currently)– a program actually looks like empty space because it is in fact

full of spaces, tabs and returns!– programming requires fully commenting your code because

you can’t actually see the code• The author claims that Whitespace is the perfect language for spies since

no one can actually see the code to make sense of it!

Page 50: Other Languages

WhitespaceOperations

White Space Parameter Meaning[Space] Number Push the number onto the stack[LF][Space] - Duplicate the top item on the stack[Tab][Space] Number Copy nth item on the stack to the top of the stack[LF][Tab] - Swap the top two items on the stack[LF][LF] - Discard the top item on the stack[Tab][LF] Number Slide n items off the stack, keeping the top item[Space][Space] - Addition[Space][Tab] - Subtraction[Space][LF] - Multiplication[Tab][Space] - Integer Division[Tab][Tab] - Modulo[Space] - Store to Heap[Tab] - Retrieve from Heap[Space][Space] Label Mark a location in the program[Space][Tab] Label Call a subroutine[Space][LF] Label Jump unconditionally to a label[Tab][Space] Label Jump to a label if the top of the stack is zero[Tab][Tab]Label Jump to a label if the top of the stack is negative[Tab][LF] - End subroutine, transfer control back to caller[LF][LF] - End the program[Space][Space] - Output the character at the top of the stack[Space][Tab] - Output the number at the top of the stack[Tab][Space] - Read character, place it in location given by the top of the stack[Tab][Tab] - Read number, place it in location given by the top of the stack

Page 51: Other Languages

Whitespace Example[Space][Space][Space][Tab][LF] Put a 1 on the stack[LF][Space][Space][Space][Tab][Space][Space] [Space][Space][Tab][Tab][LF]

Set a Label at this point[Space][LF][Space] Duplicate the top stack item[Tab][LF][Space][Tab] Output the current value[Space][Space][Space][Tab][Space][Tab][Space][LF] Put 10 (newline) on the stack...[Tab][LF][Space][Space] ...and output the newline[Space][Space][Space][Tab][LF] Put a 1 on the stack[Tab][Space][Space][Space] Increments our current value.[Space][LF][Space] Duplicate that value so we can test it[Space][Space][Space][Tab][Space][Tab][Tab][LF] Push 11 onto the stack[Tab][Space][Space][Tab] Subtraction, if we reached the end, we have a zero

on the stack[LF][Tab][Space][Space][Tab][Space][Space] [Space][Tab][Space][Tab][LF]

If we have a zero, jump to the end[LF][Space][LF][Space][Tab][Space] [Space][Space][Space][Tab][Tab][LF] Jump to start[LF][Space][Space][Space][Tab][Space] [Space][Space][Tab][Space][Tab][LF]

Set the end label[Space][LF][LF] Discard our accumulator, to be tidy[LF][LF][LF] Finish

Page 52: Other Languages

Malbolge• Designed in 1998 to be the hardest programming language ever!

– based on Intercal and Brainf*ck– instruction’s effects are based on where it is stored in memory mod 94– instructions are self-modifying– both code and pointers are incremented by 1 after being accessed

• only control statement is an unconditional jump• data are stored in trinary (0, 1, 2) rather than binary or decimal• no load or store operation, instead memory must be pre-loaded

– The above Hello World program was the most complex Malbolge program ever written for years, but a version of the 99 Bottles of Beer program has been written

• it consists of 7773 characters and is about 200 lines long of meaningless characters (see http://www.99-bottles-of-beer.net/language-malbolge-375.html if you are interested)

Hello World Program:(=<`$9]7<5YXz7wT.3,+O/o'K%$H"'~D|#z@b=`{^Lx8%$Xmrkpohm-kNi;gsedcba`_^] \[ZYXWVUTSRQPONMLKJIHGFEDCBA@?>=<;:9876543s+O<oLm

[the program is supposed to be on one line]