[Skip Navigation] [Remove Frame] [CS320] [Text Version] manual.html Sat Dec 23 08:00:22 PST 2006

Contents


    CS Languages Reference Manual March 28, 1996

      Keep this manual beside you when you are online. Scribble notes in it.... You may use it CS320 tests.

      Details on Languages

      [ http://csci.csusb.edu/dick/samples/ ] documents a dozen or more computer languages.

      [ cs320 ] has a directory of example programs for each language.

      Copyright

      Java, LISP, Prolog, Tiny Smalltalk, Gnu C/C++ & Q can be copied, modified, and used by students, staff, and faculty at CSUSB but not sold.

      UNIX File Names

      Programs normally are in a single file with a particular suffix ("extension") at the end of its name. On Unix everything is a stream of bytes and most files are text file. all are edited with the same editors! Either the names suffix or first line determines the language for the file. More complex programs use a 'Makefile' and the 'make' command.


         Language	Typical file name
         Ada	program.ada	Main program
         Ada	program.ad[spb]	Module - package specifications and bodies
         Ada	program.sub    	Subprograms

         C	program.h	Header file.  Specifications. #included
         C	program.c	Programs and modules
         C++	program.C	Programs and modules
         C++	program.cc	Programs and modules

         Java	program.java	Contains class definitions and specifications

         LISP	program.lsp	Contains function definitions
         	program.scheme	Contains function definitions
         Pascal	program.p	Complete Programs

         Prolog	program.plg	Contains predicate definitions and data

         SmallTalk	program.st	Defines classes
         	program.image	Binary
         Shell	program.sh	Commands interpreted by Bourne Shell
         	program.shar	Commands interpreted by Bourne Shell

         Archive	name.tar	Archive of Files and directories
         Compressed	Name.Z, name.z,... Compressed data/program/texts

        Q for Quick Compilation, Load, and Run

        We have some simple software that makes it easier to test simple programs using 'vi'. A single keystroke('q') saves the current version of the program, suspends the editor ('vi'), and runs the correct interpreter or compiler for the program being worked on. Afterward tap the return key to restart 'vi' as it was before the test run. To save and exit tap 'SHIFT/Z' twice. To exit, type ":q!" and tap the Enter/Return key. If you have a "Makefile" then this will be searched for 'program' and if it is a target then 'make' is invoked.

        Given a file name with no obvious language, 'Q' can run an interpreter determined by the first line in the file. If the first line starts with a ':' then the Bourne shell is used. If the first line starts with '#! program' then 'program' is used. This program name should be an absolute path name starting with '/'.

        The 'vi' editor invokes 'Q': a CSUSB shell script that describes how to interpret different kinds of file. For ed/ex a shell escape '!Q file_name' is used. Similarly for EMACS. 'Q' can also be invoked directly at any shell prompt: '$ Q file_name'. In AIX Windows and the SGIs you can "Drag-and-drop" files into a Q icon as well.

        Setting Up Q

        You have to have the directory that holds 'Q' in your PATH variable(/usr/local/bin, /share/bin, or /u/faculty/dick/bin). Then type the command 'Q setup'.

        Syntax

        BNF is a syntactically sugared context free grammar(Sebesta chapter 3). EBNF has the same power as BNF, but is easier to write. XBNF is an extended BNF that fits other mathematical notations.
         	(BNF):       <number>::=<digit>|<number> <digit>	[Naur et al 64]
         	(EBNF):     number::= digit {digit}		[ADA]
         	(XBNF):	number::= N(digit).		[Botting 9x]
        In all three forms '::=' means 'is defined to be'. Some books uses '<-' or '->'. In all three BNFs, '|' separates alternatives. In BNF the defined terms look like this <...> and the character strings used in the language being defined are printed normally. In EBNF '{...}' indicate 'zero or more of' and '[...]' indicates optional item. Also in EBNF a set of alternatives can be put into parentheses '(...|...|...)' indicating that there are several alternatives at that point in a sequence. In EBNF words in the language are typeset in bold.

        XBNF uses ASCII symbols only - white space, bars ("|") and the symbol "::=" as in BNF. The "<" and ">" of the original BNF are omitted. They are used as relations and as parts of arrows and crosses instead. Parentheses "()" are used as they are in algebra or EBNF. XBNF uses "#" to mean any number of, including zero thus letting the brace symbols "{}" of EBNF be used for sets. In XBNF "[]" are used to show subscripts and are not used for optional items, instead we write "O(....)". XBNF also lets you document terms and functions by declarations like this:

         	term ::type =`informal description`.
         	For declarations, expression::type =expression.
         	 term :: type.  properties_of_term.

        XBNF Summary

      1. | or/union, & and/intersection, ~ butnot, O(optional part ), #(optional iterated part), N(repeated part) Terminals are in strings - using the C rules for strings. Non_terminals are not between <...>.
      2. A B::={a b || a in A and b in B }.
      3. N(A)::= A #(A).
      4. #A::=O( A #(A)).
      5. O(A)::= (A|).
      6. L(A)::= A #( comma A).

        Lexemes

      7. char::=any ASCII character.
      8. digit::= "0".."9".
      9. capital_letter::="A".."Z".
      10. letter::=capital_letter | "a".."z". underscore="_".
      11. sign::= "+" | "-".
      12. comma::=",",
      13. semicolon::=";",
      14. left_bracket::="[",
      15. right_bracket::="]".
      16. quote::="\'".
      17. space::=" ".
      18. non_quote::=char~quote.
      19. l_paren::="(",
      20. r_paren::=")",...

        Mathematics in ASCII

          Sets

        1. a in A::Boolean=true if a satisfies the properties defining A
        2. A | B::={c || c in A or c in B},
        3. A & B::={c || c in A and c in B},
        4. A ~ B::={c || c in A and not ( c in B) },
        5. A >< B::={(a, b) || a in A and b in B }.

        6. Boolean::={true, false},
        7. Bit::={0,1},
        8. Natural::={1,2,3,...},
        9. Unsigned::={0,1,2,3,...},
        10. Integer::={..., -2,-1,0,1,2,...},
        11. Rational::=Fraction::=Ratios of two Integers,
        12. Real::=See mathematical texts,
        13. Float(s)::=Rationals with a power of two as a denominator and s significant bits, ...
        14. For i,j, i..j::= { k || i<=k and k<=j },
        15. i..::= { k|| i<=k},
        16. ..j::= { k || j>=k}.

          Functions

        17. For X,Y, X ->Y::=The set of functions that given an X return a Y.
        18. For X,Y,Z, X><Y->Z::=The functions that return a Z when given an X and a Y, ... These are used to declare the types of the arguments and values of a mathematical function:
        19. double::Integer -> Integer.

          We use this notation for functions :

            	fun[formal arguments](returned value).
          Definitions can attach names to functions:
        20. double::= fun[x] (x+x).
        21. double::=the function that takes x and returns x+x.

          Simple functions can be written using the symbol (_) to show the "hole" where the actual parameter is put:

        22. square::Integer -> Integer.
        23. square::= (_) * (_).

          We sometimes write:

        24. cube::Integer -> Integer.
        25. For all x:Integer, cube(x)::=x*square(x).

          We can also define a function by listing its properties:

        26. fact::Natural -> Natural.
        27. fact(1)=1 and for all n, fact(n+1)=fact(n)*n.

          To evaluate expressions with functions, use algebra, arithmetic, intelligence, and the rules below:
          Net

          1. (f1): If a term t is equal to expression d, then wherever t appears in e we can put (d) in ts place.
          2. (f2): If t(x) is equal to d for all values of x, then t(a) is equal to (d) with every occurrence of x in d replaced by (a).
          3. (f3): If an expression e has some holes(_), then (e)(a) is the result of putting a in all the holes in e.
          4. (f4): If an expression f has a (fun[x](e)) in it that is not inside another (fun...) , then (f)(a) is equal to f with the (fun[x](e)) modified by replacing each x in e by (a) and removing the fun[x].
          5. (f5): If two expressions evaluate to the same thing then they are equal and vice versa.
          6. (arithmetic): You can use your knowledge of arithmetic or a calculator to evaluate expressions.

          (End of Net)

          Example
          1. double(cube(2))
          2. (cube, f2)|-
          3. =double(2*square(2) )
          4. (square, f1)|-
          5. = double(2*((_) * (_))(2) )
          6. (f3, _:=2)|-
          7. =double(2*(2*2))
          8. (arithmetic)|-
          9. =double(2*4)
          10. (arithmetic)|-
          11. = double(8)
          12. (double, f1)|-
          13. =( fun[x] (x+x))(8)
          14. (f4, x:=8)|-
          15. = 8+8
          16. (arithmetic)|-
          17. =16.

          Logic Notation

          A proposition can has two possible meanings - true and false - the Booleans
        28. not::Boolean->Boolean.
        29. (neg1): not(true) = false.
        30. (neg2): not(false)=true.


          1. and::Boolean><Boolean=(1st) and (2nd) are both true,
          2. or::Boolean><Boolean=at least one of (1st) and (2nd) are true,
          3. iff::Boolean><Boolean=(1st) and (2nd) are the same, both true or both false,
          4. if_the_::Boolean><Boolean=either (1st)is false or (2nd) is true, :- :: Boolean><Boolean->Boolean=if (2nd) then (1st).
            P true true false false Syntax Precedence
            Q true false true false
            P and Q true false false false infix(serial) 2nd (after not and (...))
            P or Q true true true false infix(serial) 3rd
            P iff Q true false false true infix(parallel) 4th
            if P then Q true false true true natural 5th
            Q:-P true false true true infix Last

          Mathematics has two kinds of infix operator:

        31. (Serial): P1 and P2 and P3 = (P1 and P2) and P3
        32. (Parallel): P1 iff P2 iff P3 = (P1 iff P2) and (P2 iff P3).

          Predicates

          A predicate is a proposition that can have variables, quantifiers, and tests for equality.

          Equality

          Equality is a special predicate (or relation) that is defined for all types of objects. It is symbolized by "=". Inequality is shown as "<>" (like Pascal and BASIC). Equality is a parallel operator on objects. It has a higher priority than any of the logical operators so
        33. x = y = z iff x=y and y=z iff ((x=y) and (y=z)).

          Quantifiers

          Quantifiers say how many objects satisfy a particular proposition: "one", "no", "0..1", "all", "some". In the following X is a set or a type, xis a variable and W(x) a proposition containing x in a number of places.
            for all x:X(W(x))::=For all x of type X, W(x) is true, for x:X(W(x))::= for all x:X(W(x)), for no x:X(W(x))::=for all x:X(not W(x)), for some x:X(W(x))::=not for no x:X(W(x)). for 0 x:X(W(x))::= for no x:X(W(x) ), for 1 x:X(W(x))::= for some x:X( W(x) and for 0 y:X(x<>y and W(x)) ), for 2 x:X(W(x))::= for some x:X( W(x) and for 1 y:X(x<>y and W(y)) ).
          1. . . . for 0..1 x:X(W(x))::=for all y,z:X( if W(y) and W(z) then y=z),
          2. . . .

          Further reading: Texts for critical thinking and discrete mathematics courses. http://www/dick/maths/

        LISP

          Introduction

          XLISP is an experimental LISP interpreter with objects. To start it up type in the UNIX command 'lisp' or 'lisp filename...'. In LISP all code - programs, commands, subprograms, etc., are expressed as functions. It is easy to define a new function (define (f x) y) and test it (f x). It is not yet possible to edit a function once it is input.

          The best way to use LISP is to use 'vi' to edit a file with a name that ends '.lsp'. Put all the definitions in it. Use the Q program to save the file and load the interpreter with the file etc. Note: In 'vi' the '%' command jumps between matched parentheses. Use it to check your typing. Also this vi command ':set showmatch' makes 'vi' show you how much of the expression you are typing is complete.

          Syntax

          LISP ignores upper and lower case. All LISPs use some form of bracketed prefix notation. An expression is always like this:
                (function_name argument ...).
          The item after a parenthesis is assumed to be a function with its arguments after it. Constants are numbers (integer or decimal), strings ("..."), or one of two special constants:
        1. NIL = false
        2. T = true, or lists that start with the word QUOTE like this:
        3. (QUOTE data).

          The notation

        4. '( .... ) is short for
        5. (QUOTE (.....))

          Function automatically evaluate their arguments. Some operations look like functions but don't do evaluate things first. QUOTE, DEFINE, COND and IF are examples. They are called macros.

          The data processed in LISP is always a list. A list can be empty (NIL='()), an atom (word or number), a string, or several lists between parenthesis:

        6. list::=empty | atom | "(" #list ")".

          Implementation

          The data in LISP is a list. Internally it is one of three simple structures: a list is empty, atomic or a pair:
        7. list::= nil | atom | pair.

          In practice these are (1) the null pointer, (2) a pointer to a string, (3) a pointer to a structure with two components called 'car and cdr'. Thus LISP uses binary trees (CS330).

          Semantics

          LISP is based on Church's λ calculus. The basic functions are (CONS a b)::=construct a pair of a & b. (CAR p)::=first of pair p. (CDR p)::=second of pair p. (ATOM x)::=T if x is not a list. (NULL x)::=T id x is an empty list.

          More complex functions are constructed and named by using: (LAMBDA (X) E)::=The function fun[X](E). (COND pair...)::=Conditional selection of first true case. (IF B E1 E2)::=Two way "if-then-else selection

          Hints

          Discard habits that waste your time and let LISP do the work for you!
          1. Don't worry about efficiency until you have a clear solution.
          2. Don't look for a main program - write lots of small functions so that the user can pick and choose what to do.
          3. Don't waste time planning input and output - a LISP function is given lists as data by the interpreter and outputs a list as a result to the standard output.
          4. Don't think in terms of assignments, sequences, and loops. There is little need for improvisation. Just classify and decompose the arguments until they can be processed by known functions: predefined, defined later, or the function being defined.
          5. Layout LISP carefully with indented sublists.

          For example:
           	(DEFINE (length L)
           	   (COND
           	     ((NULL L)  0)
           	     ((ATOM L)  1)
           	     (   T (+ 1 (LENGTH (CDR L)) ))
           	   )
           	)
          
          

          More in http://www/dick/cs320/lisp/design

          Some LISP Functions

          XLISP has many ready made functions. Here is a partial list - the complete list is in /u/faculty/dick/cs320/lisp/functions. Optional arguments are in square brackets. e is an expression, t any condition, f any functions, s is a symbol.
           (* e...)  multiply		(+ e...)  add
           (- e...)   subtract or negate  	(/ e...)   divide
           (1+  e)  add one		(1-  e)   subtract one
          
          
           (/= e1 e2)  test for not equal to
           (< e1 e2)   test for less than
           (<= e1 e2) test for less than or equal to
           (= e1 e2)   test for equal to
           (> e1 e2)   test for greater than
           (>= e1 e2) test for greater than or equal to
          
          
           (abs e)    the absolute value of a number
           (and [e]...)  a logical and (short-circuited)
           (append [e]...)  append lists
           (apply f args)  apply a fun to arguments
           (assoc e l)  look up e in first items of a list of pairs, return other component
           (ATOM e)   is this an atom?
          
          
           (CAR e)    return the car of e
           (CDR e)    return the cdr of e
           (CONS e1 e2)  construct a new pair/node
           (consp e)  is this a non-empty list?
           (cxxr e)   all cxxr combinations(x::=a|d)
           (cxxxr e)  all cxxxr combinations
           (cxxxxr e) all cxxxxr combinations
           (char e1 n) nth character in string e1
           (COND [pair]...) evaluate a pair::=(t e)
           (case e [case]...)  select by case
        8. case::=(value [e]...)
           (cos e) (sin x) (tan x)  trig functions

           (do ([binding]...) (t) e...)  loop
           (do* ([binding]...) (t) e...)  loop
           (dolist (s list) e...) for s in list
           (dotimes (s e1) e2...) s in 0..e1-1
          
          
           (eq e1 e2)   (eql e1 e2) (equal e1 e2)
        9. Various equality tests.
           (evenp e)  is this number even?
           (exit)  exit XLISP
           (exp e)  exponential of e
           (expt e1 e2)  e1 to the e2 power
          
          
           (float e)  converts to a floating point
           (funcall f [arg]...) call function with args
           (function e)  quote a function
          
          
           (IF t e1 [e2])  if t then e1 else e2
          
          
           (LAMBDA args [e]...)  a function constant
           (last e)   return the last list node of list e
           (let (s e)... e...)
           (length e) the length of a list or string
           (LIST [e]...) constructs a list of values
           (listp e)  is this a list (not a null or atom)?
           (LOAD filename [vflag [pflag]]) load a file
          
          
           (mapc f e) (mapcar  f e) (mapl  f e) (maplist  f e)
           apply f to all (cars, cdrs, elements) in e
           (max e...) (min e...) the largest/smallest
           (member e1 e2)  is e1 an item in e2?
           (minusp e) is this number negative?

           (not e)    is this false?
           (nth n e)   the nth item of e
           (nthcdr  n e)   the nth cdr of e
           (NULL e)   is this an empty list?
           (numberp e)  is e a number?
           (oddp e)   is e odd?
           (or [e]...)  logical or

           (plusp e)  is e positive?
           (prin1 e ...) print e
           (princ e ) print without quoting
           (print e) print e on a new line
           (progn [e]... en)  execute sequentially{...}
           (prog ([binding]...) [e]...) begin...end/{...}
           (return e)  cause a prog to return value

           (QUOTE e)   return e unevaluated

           (random n) random number between 1 and n-1
           (rem e...) remainder
           (reverse e)  reverse a list

           (setq s e) set the value of a symbol
           (sqrt e)   compute the square root of a number
           (strcat [e]...)    concatenate strings
           (terpri )  terminate the current print line
           (truncate e) truncates a float to an integer
           (write-char character)  write a character
           (ZEROP e)  is this number zero?

          Useful Macros

          #'e ::= (function e) 'e::=(QUOTE e)
        10. #(e...)::= an array

          Declaring Functions etc

          (DEFINE (N args) e)::= name a new function.
        11. Afterwards N means (λ (args) e). (DEFUN N (args) e) is similar.

        Prolog

          How to run Prolog

          Our Prolog is compiled just like C or C++:
               $ pl -c file1 -c file2 ...
          where file1, file2, ... contain Prolog programs which are to be compiled. The result is put in a.out. Or
               $ pl -o program -c file ...
          If the program is in a single file and the file's suffix is .plg then Q/quickie can compile and run it.

          When the compiled program is run it responds with a ?- prompt. You then enter queries. Each query must terminate with a period but it can be just about any valid statement.

          Programs

          A program is made up of a sequence of clauses, directives, and comments. A set of clauses with the same name or functor define a predicate. They do not need to be immediately consecutive, but their relative order may be important. The text of a program is normally created separately in a file (or files), using an editor.

          To input a program from a file inside Prolog, give the command:

                 consult(Name).
          which will instruct the interpreter to find and read the file 'Name.plg'. The search starts in the standard library and then the local directory etc. When a file is loaded, a predicate of the form
                   file(FileName, PredicateList)
          is asserted to be true. FileName is the name of the loaded file and PredicateList is a list of the names of the predicates defined in the file. Once a file has been read, the interpreter can execute any of the predicates defined in the file.

          When the same file is loaded a second time, the definitions in PredicateList are first removed so that clauses in the predicates are not duplicated. Any characters following the `%' character on any line are treated as part of a comment and are ignored.

          Directives

          Directives are ways of directing the compiler to execute some goal or goals during the compilation process. Typically like this:
           	:-op( =>, xfx, 9000).

          Responses Queries

          Suppose list membership has been defined by:-
           	member(X, [X|_]).
           	member(X, [_|L]):- member(X, L).
          The command:
           ?- member(3,[1,2,3]), write (ok).
          makes Prolog check whether 3 belongs to the list [1, 2, 3], and to output "ok" if so. The program then waits for ';' (Prolog for "or"), and will then search for another solution. If no solution can be found, the system simply returns "No" and a prompt.

          The final value of each distinct variable is displayed. The outcome of some queries are shown below.

           ?- member(X, [tom, dick, harry]).
           X = tom
           Yes  ;
           X = dick
           Yes  ;
           X = harry
           No
           ?-
          You input the semicolons above.

          Editing definitions

          It is possible to edit predicates/data within Prolog. To edit the definition of a predicate taken from a file, use the command:
                        ed (PredicateName).
          Your standard text editor will automatically be called on the original file at the first definition of that predicate. When the editor is exited, Prolog will replaces the old definition with the edited form. The file is also changed. You can specify which editor by assigning the name of the editor to the UNIX environment variable EDITOR. This should be done before running Prolog.

          Saving Program & Data

          The database may be saved for future use. To save it into a file, perform the command:
                     save ('File.plg').
          The result is a text file which can be edited normally. Definitions are in an arbitrary order. The database can be restored later by executing,
                            consult(File).

          Execution And Interruption

          Execution of a predicate starts when you input it as a query. Only when execution is complete does the program become ready for another directive. However, one may interrupt the normal execution of a directive by typing CTRL/C. This interrupt signal has the effect of terminating the execution of the command. Prolog will then respond with a prompt.

          Execution may also be terminated if the program runs out of stack space. Warning: make sure that the reason the program ran out of stack space was not due to an error in your program before increasing the size.

          Tracing

          Prolog interpreter provides a tracing facility. This turned on by input:
           ?- trace. query.
          and stays on for that one query only. Predicates may be individually traced enabling each event involving the predicate to be displayed on the terminal with the current values of its arguments.

          The events traced

                 Call      Exit      Fail      Redo

          Call' indicates that a predicate is being called for the first time. A line beginning with Exit' shows the interpreter exiting a clause after all the goals have been satisfied. Fail' indicates an exit from a clause due to a failure in satisfying a goal. After a failure, Prolog will attempt to redo a predicate call if there are alternative clauses left in the predicate definition. This is shown by an Redo'.

          After reporting the program waits for one of a number of actions by the user - 'h' gives a list of possibilities, 'a' aborts execution and tapping return lets the program continue An example of tracing output is shown below:

           	?- trace. member(X, [1,2]).

          Exiting From The Interpreter

        1. To exit from the interpreter and return to the shell type ^d (control d) or the command halt. .

          Syntax

          A program is a set of definitions, the data is a set of definitions, and even the queries are input using the same notation! In Prolog: data and program are stored using the same notation and in the same structure. The basic notation is a predicate in "functorial form":
           	functor ( part, part, part, ... ).
          It is stored like a record structure. Its meaning varies depending on the context - it can be data, program, or an axiom. A definition is made of "clauses":
           	predicate:-predicate, predicate,.... .
          and each predicate is in functorial form above.

          A comment starts with a '%'.

          Operators and precedences

          Prolog already understands mathematical style operators. Prefix, infix and postfix operators can be defined:
           fx	prefix part       ( - X, good X))
           xfx,...	part infix part   (X + Y, X has Y)
           xf	part postfix      ( X!,  X?)

          Variables vs constants

          In Prolog a variable has an uppercase letter or an underscore(_) as its first character. All other identifiers, operators, and numbers are atomic constants. An identifier (starting with a lower case letter is called an atom.

          Strings are also constants. Single quoted strings are treated like an atom - even if they begin a capital letter. Double quoted strings indicate an array of integers for the ASCII codes of the contents of the string.

          All variables are temporary and local. Prolog works by searching for values for its variables. These are called instances. Prolog links an instance to a variable - and variable together. It keeps adding facts and deducing values until it has solved the problem or until it can not find a value that fits a variable, or it would have to change a value of a variable!

          Once an instance has been found it is fixed until Prolog is forced to go back and undo the command that found it. At the end of a search all variables loose their values. The only permanent storage for data as facts or definitions. 'assert' and 'retract' manipulate them.

          Unification

          Variables get temporary values by a process called unification. Alternative definitions can uncover new temporary values. Each is an instance and the variable is then said to be instanciated.

          Unification forces two expressions to match by (1) instanciating variables as constants, and (2) making them identical. This is done, piece by piece throughout the two expressions, in parallel. For example X+Y*3 matches 1+X*Z when X=Y=1 and Z=3. Unification does NOT evaluate expressions.

          Prolog uses unification whenever it calls a predicate. The name of the predicate is found in the data base and the arguments in the data base are unified with the arguments in the call. So if

           	a(1). a(2).
          is in the data base the query:
           	?- a(X)
          will generate
           	X=1
          and
           	X=2
          in turn.

          Equality

          It as if the fact
           	X=X
          is the only fact on file. The query
           	?- A=1+B, B=3.
          first invokes X=X with X unified to A and 1+B. So, A=1+B. Then B unified with X, and X with 3. So A=1+3 and B=3. The 1+3 is not evaluated, So,
           	A=1+3
           	B=3
          is output.

          Evaluating Expressions

          In
           	?- B=3, A is 1+B.
          A is instanciated to 4 rather than 1+3! The same thing happens here:
           	?- C = 1+B, B=3, A is C.
          Evaluation only occurs in certain predicates:
           	is,<,>,<=,\=,>,=<
          In X is E the E is evaluated and X becomes the value or else X tested vs. result. Evaluation is on the RHS of 'is' only. In these E1<E2, E1<=E2, E1\=E2, E1>E2, and E1>=E2, E1 and E2 are evaluated and compared.

          Expressions

           + A 	- A         A * B 	A + B
           A - B	A / B     A mod B

          Plus the following "functions": abs,acos, asin, atan, ceil, cos, cputime, e, exp,float,float_fractional_part, float_integer_part, floor, integer,log, log10, max, min, random, rem, round, truncate, pi, sign, sin, sqrt, tan, xor.

          Predicates

          This Prolog comes with hundreds of predicates. See
           	http://www/dick/samples/prolog.predicates.html
          Here is a short list of useful onese(IMHO). abolish, abort, append, apropos, assert, asserta, assertz, atom, atom_length, atom_to_term, atomic, bagof, between, clause, concat, concat_atom, consult, debug, debugging, ed, edit, exit, fail, findall, forall, functor, garbage_collect, gensym, get, get0, get_single_char, get_time, getenv, ground, halt, help, is, last, length, maplist, member, merge, name, nl, not, notrace, nth0, nth1, once, op, print, prompt1, prompt, put, read, read_clause, repeat, retract, retractall, reverse, setof, shell, sleep, sort, spy, statistics, string, string_length, string_to_atom, string_to_list, tab, tell, telling, told, trace, tracing, true, union, var, write, write_ln.

          Hints

          Prolog programming is best started 'declaratively'. This means:- "the truth. the whole truth, and nothing but the truth".

           (1) declare facts and rules that describe the situation.
           (2) get them in the right order for Prolog to find solutions.
           (3) look for ways to cut off unwanted solutions.

        Tiny Smalltalk

         unix $ st
         unix $ st old_image
         unix $ st old_image  new_image
         The prompt is
         	>
         Typing control-D causes the interpreter to exit.
         Lexical
         strings - '....',  characters - $.,
         arrays - #(...),
         symbols - #...,  blocks - [...] [...|...]
         numbers - decimal integer & floating point etc.
         Comments: "...."
         Classes have an uppercase letter first.
         In an identifier words start with a capital.
         A "\" is put at the end of line to continue it to the next line
         To see info on an object X
         	> X display
         	> X
         Assigning a name N to the result of E
         	N <- E
         Making a New Object  of class X
         	X   new
         	X   new; initialization
         	N <- X   new; initialization
         Arrays and strings need a number
         	X   new: Size
         	...
         To see Info on class Y
         	> Y display
         	> Y methods
         	> Y viewMethod: #M
         Adding a new class X as a subClass of Y
          >       Y addSubClass
         	...
         Adding a method to class X
           >       X addMethod
         Enters 'vi'. Use vi to describe the new method
         	template
         	| variables | commands
         and then ZZ or :wq back to Smalltalk.
         Editing a Method M of Object X
           >       X editMethod:   #M
        
        

        Initial Classes, Methods & Objects

        Block
        1. whileTrue: whileTrue value:value: value: value:value:value: value checkArgumentCount:
        2. syntax( [...], [ :x | ...], [ :x :y ...| ...] )

        Boolean
        1. or: and: ifFalse:ifTrue: ifTrue: ifFalse:
        2. False
          1. not ifTrue:ifFalse:
          2. false is an object in class False.

        3. True
          1. not ifTrue:ifFalse:
          2. true is an object in class True


        Class


        1. addMethod addMethodText: addSubClass display doEdit: editMethod: fileInMethod: fileOut: fileOutMethod:to: initialize instanceSize methods name name: new new: printString readInstanceVariables readMethods respondsTo respondsTo: subClasses superClass superClass: upSuperclassChain: variables variables: viewMethod:

        Context
        1. executeFrom:creator: arguments: method: temporaries: temporaries

        File
        1. open: saveImage close delete fileIn getString inquire: printNoReturn: name print: asString fileInMethod: scratchFile getPrompt: readUntil:doing: name: fileInClass:

        Link
        1. includesKey: removeValue: size value at:ifAbsent: binaryDo: add:whenFalse: at:put: link: removeKey: key: value:

        Magnitude
        1. = < > ~= <= >= between:and: max: min: {Subclasses on next page} [ Magnitude ]

        Method
        1. name display printString executeWith: message: text text: compileWithClass:

        Object
        1. display class == isNil = printString notNil isMemberOf: basicSize isKindOf: new hash print basicAt: basicAt:put:


        Random
        1. between:and: next next: randInteger: set:


        Smalltalk
        1. load: cantFindGlobal: saveImage doIt: openFiles error: commandLoop class:doesNotRespond: flushMessageCache
        2. smalltalk is an object in class Smalltalk


        Switch
        1. key: ifMatch:do: else:


        Symbol
        1. asString in: is: printString respondsTo
        2. syntax (#...)


        UndefinedObject
        1. printString notNil isNil

        Magnitude

        (All subclasses of magnitude(below) inherit these methods = < > ~= <= max: >= between:and: min: )
        1. Char
          1. < = == asInteger asString digitValue isAlphabetic isAlphaNumeric isBlank isDigit isLowercase isUppercase printString value:
          2. syntax ($.)

        2. Number
          1. / * + - < = ceiling coerce: exp floor fractionalPart generality integerPart ln printString rounded squared sqrt truncated
          2. Float
            1. / * + - < = ceiling coerce: exp floor fractionalPart generality integerPart ln printString rounded sqrt truncated

          3. Fraction
            1. / + * - < ... Note( Integer / Integer returns a Fraction )

          4. Integer
            1. //(div) / * + - < = \\(mod) allMask: anyMask: asCharacter asDigit asFloat asString bitAnd: bitAt: bitInvert bitOr: bitShift: bitXor: even factorial gcd: generality lcm: odd printString quo: radix: rem: timesRepeat:
            2. LongInteger
              1. + * / - ...



        3. Collection
          1. < = asArray asByteArray asSet asString display includes: inject:into: isEmpty occurrencesOf: printString size sort sort:

          2. List
            1. add: add:ordered: addAll: addFirst: addLast: collect: do: first reject: remove: removeFirst select: size
            2. Set
              1. add:


          3. Interval
            1. do: first inRange: lower: next step: upper:

          4. IndexedCollection
            1. addAll: asArray asDictionary at: at:ifAbsent: binaryInject:into: collect: do: indexOf: indexOf:ifAbsent: keys select: values
            2. Dictionary
              1. at:ifAbsent: at:put: basicRemoveKey: display hash: binaryDo: includesKey: new removeKey: removeKey:ifAbsent:
              2. Array
                1. < = at:put: binaryDo: copyFrom:to: do: exchange:and: includesKey: size with:do:
                2. syntax ( #( ... ... ... .... ) )
                3. ByteArray
                  1. asString basicAt:put: basicAt: size size:
                  2. String
                    1. , < = asInteger asSymbol basicAt: basicAt:put: copy copyFrom:to: edit input load print printNoReturn printString size unixCommand words:
                    2. syntax( '...' )








      Saving and quitting

      Saving a Session for later
            >       smalltalk saveImage
            Image name? N
            image N created
      Typing control-D terminates Smalltalk. The image N can be restarted by 'st N' To Save a class Foo in ASCII file Foo.st
            >	Foo  fileOut
      Loading ASCII File Foo.st
            >       'Foo.st' load

      Outputting ASCII foo.st

            >       f   <- File new
            >       f name: 'foo.st'
            >       f open: 'w'
            >       Foo fileOutOn: f
            >       Foo fileOutMethod: #M   to: f
            >       f close

      Doing a Unix Command

       	>	   'command '  unixCommand

    Java

      Introduction

      Java can be used to create normal "applications" or small little programs that can be sent across the internet and executes on a different system entirely. These are called Applets. These notes will focus on creating and running applications.

      How to run Java

      Java code is put into a file with suffix or extension .java. Each file has classes declarations. The file is compiled by
       	javac filename
      After compilation each class (or package) is in a file with name
       	ClassName.class
      Documentation is generated by
       	javadoc filename
      and put in file with name
       	ClassName.html
      Hint: Notice where the UPPER and lowerCase letters are... Java is toTaLlY SensItIve to case in its filenames. HelloWorld is not helloworld.

      Java Applications

      An Application is any class that has a main method(function) like this:

       class Hello {
        public static void main(String argv[]){
         System.out.println("Hello, World!");
        }
       }

      You run an application from the terminal by

       	java ClassName

      Q/quickie automates the above:

       	Q filename

      Java - the language

      Java borrows must of its syntax from an early non-standard version of C++. 90% of it is instantly readable by C and C++ programmers. They have discarded powerful features of C++ and C - pointers for example.

      A class declaration:

        modifiers class name
          extends parent{
           field declaration...
           method declaration...
        }

      A field declaration:

        modifiers type name;
      or
        modifiers type name=value;
    1. A method declaration:
        modifiers type name(arguments){_
       		body
        }

      Modifiers

      include:
       	public, private, static, final, abstract, ...

      Data types

       boolean, byte, short, int, char, long, double, and any declared class.

      Predefined Classes

      Like Smalltalk and Standard C++ Java comes with a large library of classes that make things easier for a programmer who understands them. This includes the AWT - A Windowing Toolkit (or some such).

      Predefined classes include:

       String, Number, Integer, Double, System, Applet,  Class, ....

      Java Applets

      An Applet must be declared as extending the class Applet. It is invoked via HTML and a worldwide web browser.

       class HelloWorld extends Applet {
        public void init() { resize(150,25);
        }
        public void paint(Graphics g) {
           g.drawString("Hello world!", 50, 25);
        }
       }

      Java Interfaces

      Java classes they form a hierarchy. All classes extend Object. Unlike C++ a Java class can not extend more than one other class.

      It is possible to declare a set of common features that can be shared by several classes not by inheriting them but by implementing them - the common features are called an "interface" and are defined only from the caller's point of view.

      An interface declaration:

       interface Order{
          public boolean lessThan(Object y);
       }//Order

      Using an interface:

       class OrderedInt implements Order{
         protected int me;
         public OrderedInt(int i){me=i;}
         public boolean lessThan( Object y)
           {return me < ((OrderedInt)y).me;}
       }

      Java Documentation

      Java is still rapidly evolving -The documentation for whichever Java is running on a system is kept online on that system. You should learn to search it there. Please do not print out the reference manual or tutorials... you will break our printing budget.
       	http://www/dick/samples/java.html

      Java Hints

      When things do not work, check the cAsE of the files and the identifiers.

      When something works in an application but not in an applet - ask yourself it is trying to do something that is insecure - like reading a file on a foreign system.

      Check the CLASSPATH!

      I have the FAQs, links to examples, and Usenet discussions online - find them and use them.

    . . . . . . . . . ( end of section Java) <<Contents | End>>

End