Exploring APL Programming Language and Its Unique Features

other languages n.w
1 / 65
Embed
Share

Dive into the world of APL, a concise and powerful programming language developed in the 1960s. Explore its array-based operations, exceptional mathematical expressiveness, and compact program size. Discover how APL simplifies complex mathematical operations and enhances programming efficiency.

  • APL Language
  • Array Operations
  • Math Expressiveness
  • Compact Programs
  • Programming Efficiency

Uploaded on | 40 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. Other Languages We wrap up our examination of programming languages by briefly considering a wide variety we will look at some historical 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 JCL scripting language to control IBM mainframes a couple of the newer languages of note bizarre languages esoteric languages (bizarre for bizarreness sake) obfuscated languages (extremely hard to understand on purpose)

  2. APL APL a programming language (literally) developed in the early 1960s for IBM mainframes (primarily the IBM 7090 and then the IBM 360) interactive (interpreted) meant to be a language to express mathematical ideas, particularly via multidimensional arrays many built-in array operations using special character sets this allows you to write complex mathematical operations in just a few instructions these primitives can be strung together in a single line of code as a combination of array manipulations 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)

  3. APL Keyboard with Symbols Program to compute determinant of array A

  4. 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 array root, trig, logarithms, exponents separate the whole and fractional parts of a number convert numeric bases random numbers rearrange array sizes and dimensions 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,12 12 A=X(j) L=J 15 CONTINUE Y(I)=A 20 X(L)=100000. WRITE(6,30) (Y(I),I=1,N) 30 FORMAT(E15.2) END APL Array sorting program FORTRAN Array sorting program

  5. 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 of the prime numbers ending at 20 See http://www.users.cloud9.net/~bradmcc/APL.html for an explanation (halfway down this page)

  6. BCPL Basic Combined Programming Language, the precursor of C (also B) block structured like Algol syntactically somewhat similar to Algol but introduced the { } for blocks early keyboards required the use of $( and $) was typeless had only 1-D arrays case insensitive for identifiers all reserved words start with upper case letters all of C s control structures but included an Unless-Do and Repeat-Until (later found in Pascal/Modula) and loop (infinite loop) for loop more primitive than C s test-then-else rather than if-then-else

  7. More on BCPL Only one datatype: the word Words were then interpreted based on operations e.g., if used in an arithmetic expression then integers no type checking was performed All variables are locally declared or placed in a globally shared vector this vector could then be referenced in separate subroutines subroutines could be compiled separately subroutines included both functions and procedures Parameters passed by value only to change a parameter, it must be placed in the global vector

  8. BCPL Examples 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 } Manifest declares constants Let declares functions, procs 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 } 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 }

  9. 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 are placed on and taken from a stack operations must be specified in postfix notation example: 3 5 4 + * . (3 + 5) * 4 = 32 pushed on the stack, the ending period pops the top of the stack and returns this value 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

  10. Variables and Words To define a variable use variable name allocates storage for an integer in a dictionary Referencing name puts the address within the dictionary on the stack (thus, we are dealing with a stack of pointers) ! stores stack values into a variable as in variable year 2005 year ! @ fetches variable and places it on the stack year @ . arrays and strings available, index precedes variable name 10 array ! To define a subroutine: :name body; adds the new routine (called a word) to the dictionary 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

  11. 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 then uses the result If statements: If operator statement(s) then ; If < @ x * ! then ; if item on top of stack < second item retrieve x, multiply by top of stack (-1), push result 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 until and while repeat begin statement(s) condition until . begin condition while statement(s) repeat .

  12. SNOBOL SNOBOL (String-oriented Symbolic Language) dates back to 1962, standard version, SNOBOL 4 was implemented in 67, interpreted language (with a compiler) Contains the following features string manipulation operations numerous operations to test for string patterns and replace them regular expression pattern matching dynamically typed - no type declarations, variables may take on any type at any time user-defined data structures SNOBOL statements are of the form label statement :(label2) label and :(label2) are optional, :(label2) serves as a goto executed after statement (you can also use :F(label) and :S(label) to branch on instruction failure or success

  13. Sample SNOBOL Program &TRIM = WORDPAT = BREAK(&LCASE &UCASE) SPAN(&LCASE &UCASE "'-") . WORD COUNT = ARRAY('3:9',0) 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 = 2 PRINT I = I + 1 OUTPUT = LPAD(I,5) LPAD(COUNT<I>,20) :S(PRINT) END 1 READ This program inputs a text file and reads each word and counts the number of 3-letter, 4-letter, , 9-letter words and reports on the number of each found

  14. JCL Developed by IBM for its mainframes JCL instructions are interspersed along with your source code and data JCL used to specify how the OS should run batch jobs locations of files (input file, output file, compiler) also allows you to specify where to put the compiled code what to do in case of a failure such as input failure divide program and data scheduling information including priority of job Scripting language because the IBM mainframe OS interprets each instruction to determine what to do

  15. JCL Instructions Instructions placed one per punch card or, if there is no punch card input, the instructions are specified as // instruction instructions are 80 characters long, and continued on the next line if needed comments placed in //* notation types of instructions included data access (bind name to specific I/O device and file) conditional processing (based on the result of an operation, doing some other step), referbacks (for multi-step jobs, referring back to a prior instruction) procedures (grouping instructions together)

  16. Example JCL Code Data access instructions use DD //INF DD DSN=MYFILE01,UNIT=DISK,SPACE=(TRK,80,10), // DCB=(LRECL=100,BLKSIZE=1000), // DISP=(NEW,CATLG,DELETE) Job parameters uses JOB //MYJOB JOB (1A23F), FRANK ZAPPA ,CLASS=A,PRTY=3, // NOTIFY=&SYSUID Exec specifies the actual program code //MYJOB EXEC PGM=F77PROG,PARM=ZAPPA // cards containing program code here //DATA // cards with the data go here

  17. Example //COMPILE JOB ,CLASS=6,MSGCLASS=X,NOTIFY=&SYSUID //* //STEP1 EXEC IGYCRCTL,PARM=RMODE,DYNAM,SSRANGE //SYSIN DD DSN=MYDATA.URMI.SOURCES(MYCOBB),DISP=SHR //SYSLIB DD DSN=MYDATA.URMI.COPYBOOK(MYCOPY),DISP=SHR //SYSLMOD DD DSN=MYDATA.URMI.LOAD(MYCOBB),DISP=SHR //SYSPRINT DD SYSOUT=* //* //COBBSTEP JOB CLASS=6,NOTIFY=&SYSUID // //STEP10 EXEC PGM=MYPROG,PARM=ACCT5000 //STEPLIB DD DSN=MYDATA.URMI.LOADLIB,DISP=SHR //INPUT1 DD DSN=MYDATA.URMI.INPUT,DISP=SHR //OUT1 DD SYSOUT=* //OUT2 DD SYSOUT=* //SYSIN DD * //CUST1 1000 //CUST2 1001 /*

  18. Mouse 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 program s size will tend to be very short (in terms of byte length) variables and commands are made up of single characters only Mouse includes conditional branches loops pointers macros arrays code tracing

  19. Mouse Examples Below is an example of some Mouse commands 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 Example Mouse program (code on the right explains it) 1 N: ( N. N. * ! N. 10 < ^ If N < 10 then exit N. 1 + N: N = N + 1 $ End Program N = 1 Print N * N

  20. Groovy Extension to Java with the following features == compares data (whether primitive or the values that make up an object, not references) ; not needed unless multiple statements are on the same line operator overloading tuple (like Python s) functions can be passed as parameters two for loops, a C-like one and a Python-like one closures have built-in iterator operations automatically generated mutators and accessors for all private data members

  21. Lua Dynamically typed scripting language very small language that is very extendable fits three paradigms partially OO (no built-in support for inheritance) but can be expanded to include inheritance and AOP imperative control statements like Pascal s functional borrowing aspects from Scheme language treats functions as first class entities also handles concurrent programming basic unit of storage is known as a table a heterogeneous associative array local and global (the default) variables types include numbers, strings, Booleans arrays, sets, records and lists are implemented using tables

  22. Metatables One of Lua s greatest strengths is the metatable attached to every variable that contains data, it describes the variable (how it should be treated under various conditions) the metatable can be manipulated through program code add or alter a metatable entry using name.__entry = where name is the name of the variable and entry is the metatable element Example of what we might use a metatable for variable x is not a string but we want to know its length metatable(x).__len this will either return x s length or compute it metatable entries exist for a number of useful features such as length, index, concat and eq

  23. Go A systems programming language from Google that combines features of C/C++ and Python for instance, semicolon is only used to separate elements in the for loop 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 language supports the development of ontologies (as used for the semantic web)

  24. Example Code func sum(a []int) int { s := 0 for i := 0; i < len(a); i++ { s += a[i] } return s } 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). 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 } bottles(0) => "no bottles of beer". bottles(1) => "1 bottle of beer". bottles(i) => i^0 <> " bottles of beer". }

  25. 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 We will break these down into 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

  26. False One of the first obfuscated languages, it uses postfix notation for operations like Forth/Mouse operators include _ (unary minus), =~ (not equal), ~ (not), assignment (:) and dereferencing (;) a;1_=~ means a <> -1 a;0>a;99>~& means a>0 and a<99 data types are limited to integer and character (single quote like LISP s symbols), variable names limited to single letters 1a: means a = 1 a;1+b: means b = a + 1; False uses an implied stack all operations are via stack, that s why the language uses postfix functions are lambda functions placed inside of [ ] where parameters are taken from the stack based on the number of values that precede the function call

  27. 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 Control instruction are limited to if-then-else and while loop if syntax does not use an explicit word if , each clause ends with ? 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 has lambda function (condition) followed by lambda function (body) followed by # [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;}

  28. False Examples Output is [ literal ], [var], [.] or [,] (the last two print top of stack as either number or char) Input follows the ^ symbol which means stdin 2[1+]! [1+] adds 1 to the argument passed, so this code returns 3 [1+]i: defines function i, called as valuei! and the function returns value + 1, for instance 2i! 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 until character is -1 [$1=$[\%1\]?~[$1-f;!*]?]f: function f(x) = 1 if top of stack = 1, f(x-1) otherwise

  29. 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 [

  30. BF Examples BF Hello World program (creates the integer values for ASCII Hello World and outputs these values) ++++++++++[>+++++++>++++++++++>+++>+<<<<-]> ++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>. This program multiplies the original input value by 10 and stores the value back into the array Input text and output it backwards: [>+<-]> >>++++++++++ ; load 10 into fourth element [ <<[<+>>+<-] ; add num2 to first and third element >[<+>-]> ; num2=third element - ; loop ten times ] <<[-]< ; clear num2 # ; move num one right ie num2=num >.+[>.+]<[-.<] Program to compute 4 + 3 and output the result: ,>++++++[<-------->-],,[<+>-],<.>.

  31. Argh! Commands are single letters and the execution of the program is based on the commands and orientation of the commands in a 2D grid j world lppppppPPPPPPq hello, 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)

  32. Argh Commands h, 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 execution s/S - store (push) value of the cell below/above the current cell to stack d/D duplicate/delete top value on stack a/A - add value of cell below/above current cell to the value on top of the stack r/R - reduce the value on top of the stack by the value of the cell below/above f/F - fetch (pop) value from top of stack and store to cell below/above p/P - send value below/above the current cell to stdout g/G - get one byte from stdin and store in cell below/above e/E - insert value of system EOF in cell below/above Argh! and Aargh! allow self-modifying code instructions can be used to overwrite instructions!

  33. Kipple Stack-based language using 26 built-in stacks each based on a letter of the alphabet where i and o are reserved for pre- execution input and post-execution output there are no variables in a program, instead references to the top of a stack all values are treated as ints, characters converted to ASCII, strings are pushed onto a stack one char at a time use @ to interpret int as a character (only used for output) goal of this language is minimalism a language with very few commands Commands are limited to pushing/popping off of stacks > as in 5 > a (push 5 on a) or a > b (pop top of a, push to b), can also use < adding/subtracting two stack items or one stack item and one numeric operand as in a + 5 (pops top of a, adds 5, pushes result) or a + b (pops top of a and b, pushes sum onto a) clear a stack using ? as in a? loop to iterate while stack is not empty as in (a body) where body is the loop body

  34. Kipple Example 1 # Prints the lyrics to the famous "99 bottles of beer" song 99>n # push 99 onto stack n (n 10>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 # while n is not empty # 10 is ascii for new line , push new line onto s (s>o) # take everything in s and move it to o (output stack)

  35. More Kipple Examples # Prints the 25 first Fibonacci numbers # Bubblesort by DeathPing 24>n 0>t 1>a (i d+1 (b>c 0>b? x?) (x? d+0 d>f) ) (c>i) ) 0>d? (f>o) # push fibonacci numbers onto stack t (n-1 a+0 t<a>b+a c<b>a<c n? ) # Reverse (i>r)(r>o) # output numbers: (t>@ (@>o) 32>o ) # Unix cat (i>o)

  36. Chef Another stack-based programming language Difference here is that all instructions are written in English using cooking terminology that is, a program is a recipe ingredients represent integer or character values for data dry ingredients are numeric values liquid ingredients are characters (stored as int ASCII values) 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 next slide) recipe steps reference mixing bowls, baking dishes which are stacks 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)

  37. 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

  38. 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 through Verb [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)

  39. Example: Compute Fibonacci Fibonacci Numbers with Caramel Sauce. Ingredients. 100 g flour 250 g butter 1 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.

  40. Caramel Sauce. Continued Ingredients. 1 cup white sugar 1 cup brown sugar 1 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.

  41. Shakespeare Like Chef but instructions are in the form of a play with characters (variables) and scenes (subroutines) reserved words are based on whether a word is a verb, noun or adjective, or character characters declared at the top of the play in a Dramatis Personae section each character represents its own stack 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

  42. 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 has all present characters leave at the same time [Enter Juliet] [Enter Romeo and Juliet] [Exeunt Romeo and Juliet] scenes consist of lines of dialog lines are commands and fall into three categories control statements (see the next slide) I/O statements prefaced with the expression Open your heart (input) or Speak your mind (output) assignment statements (see the next slide)

  43. 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 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 is based on whether the dialog uses first person or second person 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

  44. 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 No loops construct loops like in assembly language by combining selection statements and go to statements

  45. Example: Reversing an Input String Othello, 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]

  46. 4DL Another stack-based language operators manipulate either the top of stack, or locations of a 4-D array operations are single characters instruction pointer (program counter) moves based on the direction that the current instruction steers it so program code is not sequential this is similar to Argh! however here we have four different directions we can move by incrementing or decrementing i, j, k, l (the 4-D array s four indices)

  47. 4DL Instructions Push items adjacent to the current instruction pointer location onto a stack push i+ takes the character at (i+1, j, k, l) and push it onto the stack Add or subtract top two items of the stack Pop item off stack, if not zero, skip the next coordinate in the current direction (skip next instruction in current direction) Skip 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/output from stack

  48. Example Hello 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

  49. Velato Literally a musical language instructions specified as notes in a MIDI file functional programs can be played (audio) and may actually sound pleasant according to one web site, they tend to sound like jazz songs start with a root note which doesn t do anything instructions are based on the transition from note to note this is described on the next slide chords (combined notes) are considered multiple instructions where the instructions are executed based on the order that the notes would appear in the MIDI file

  50. Velato Instructions Instruction types variable declaration minor 6th assignment minor 3rd followed by the expression block major 3rd while loop ignore next note, third note is a major 3rd followed by the expression and the while loop ending on a perfect 4th if perfect 5th followed by the condition and if clause followed optionally by an else major 6th, end if major 7th output perfect 5th followed by item(s) to print input major 6th Expressions have any number of notes in them first note is a value if it s a 3rd note second note is a variable (2nd), - (3rd), + (5th), character (4th), = (2nd), > (3rd), < (4th), NOT (5th), AND (6th), OR (7th) Third note is open paren (6th) or close paren (2nd)

Related


More Related Content