Welcome to the Dictionary of Programming Languages, a compendium
of computer coding methods assembled to provide information and
aid your appreciation for computer science history.
Browse the dictionary by clicking on a section:
A
B
C
D
E
F
G
H
I
JK
L
M
N
O
P
QR
S
T
UV
WXYZ+
Get a full dump of the dictionary:
List of Names
Short Form
Full Form
HOW TO RETURN index doc: PUT {} IN where FOR line.no IN keys doc: TREAT LINE RETURN where TREAT LINE: FOR word IN split doc[line.no]: IF word not.in keys where: PUT {} IN where[word] INSERT line.no IN where[word]
PROGRAM ONE WHEEL " Simple model of a dynamical system " written in ACSL 1, circa 1982. INITIAL CINTERVAL CINT = 0.05 ALGORITHM IALG = 4 $ "RK3" CONSTANT X1IO = 0.0, X2IO=0.0, X1DIC=0.0, X2DIC = 0.0 CONSTANT M1 = 25.0, M2=2.0, DF=100.0, K2=5000 CONSTANT TDONE = 15.0 K1 = 1000.0 END $ "OF INITIALIZATION" DYNAMIC DERIVATIVE X3= STEP(0.0) X1D = INTEG((-DF/M1)*(X1D-X2D) - (K1/M1)*(X1-X2), X1DIC) X2D = INTEG((-DF/M1)*(X1D-X2D) - (K1/M1)*(X1-X2), ... (K2/M2)*(X2-X3*5.0), X2DIC) X1 = INTEG(X1D,X1IO) X2 = INTEG(X2D,X2IO) END "OF DERIVATIVE SECTION" TERMT(T .GE. TDONE) END "OF DYNAMIC SECTION" END "OF PROGRAM"
-- simple programming with floating-point #s with Ada.Float_Text_IO; use Ada.Float_Text_IO; procedure Think is A, B : Float := 0.0; -- A and B initially zero; note the period. I, J : Integer := 1; begin A := B * 7.0; I := J * 3; B := Float(I) / A; Put(B); end Think;
/* An Alef program to parse numbers out of * the string returned from /dev/time, and * print them from a separate proc. This is * a rather lame conglomeration of several * examples from Bob Flandrea's Alef * User's Guide */ tuple(int, uint, byte*) strtoui(byte* str, int base) { int val; while(*str != 0 && whitespace(*str)) str ; if(str == nil || *str == 0) return(0, 0, str); while(*str && !whitespace(*str)) { if(!validdigit(*str, base)) return (-1, val, str 1); /* extract digit into val */ str ; } return(1, val, str); } void receive(chan(uint) c) { int s; s = <-c; print("%d\n", s); if (s == 0) terminate(nil); } void main(void) { chan(uint) c; alloc c; proc receive(c); int ret; uint val; int fd; byte *p, buf[128], *newp; fd = open("/dev/time", OREAD|OCEXEC); if (fd >= 0) { read(fd, buf, sizeof(buf)); for(p = buf; *p; p = newp) { (ret, val, newp) = strtoui(p, 10); if(ret >= 0) c <-= val; if(ret == 0) break; } } }
// the main program, calculate the mean of // some numbers begin integer N; Read Int(N); begin real array Data[1:N]; real sum, avg; integer i; sum:=0; for i:=1 step 1 until N do begin real val; Read Real(val); Data[i]:=if val<0 then -val else val end; for i:=1 step 1 until N do sum:=sum Data[i]; avg:=sum/N; Print Real(avg) end end
Here is a better example, written in the
Algol60 publication language, from
Jean Sammet courtesy of
Glyn Webster.
procedure problem (a, b); value a, b; integer a, b; begin integer k; real e; for k := 2 × (a ÷ 2) 1 step 2 until b do begin e := if prime(k) then sqrt(3 × k sin(k)) else sqrt(4 × k cos(k)); if prime(k) then putlist(k, e, 'prime') else putlist(k, e, 'nonprime') end end problem;
-- Use the Finder to close all applications -- (by Joshua D. Baer) property specialApps : {"Finder"} tell application "Finder" set allApps to name of processes end tell repeat with someParticularApp in allApps if specialApps does not contain someParticularApp then tell application someParticularApp activate quit end tell end if end repeat
;; Very simple example of interactive extension ;; for AutoCAD (Defun c:SF2ACRE () (setq SF (getreal "Enter area in square feet: ")) (setq AGREAGE (/ SF 43560.0)) (alert (strcat "\nThe area in acres is " (rtos ARGEAGE 2 2))) )
BEGIN { if ("'$#argv'"==1) Col="'$1'"; else Col=1 } {Total = $Col; }; END { printf "Total for column %d with %d items: %d\n", Col,NR,Total }
HOW TO RETURN index doc: PUT {} IN where FOR line.no IN keys doc: TREAT LINE RETURN where TREAT LINE: FOR word IN split doc[line.no]: IF word not.in keys where: PUT {} IN where[word] INSERT line.no IN where[word]
PROGRAM ONE WHEEL " Simple model of a dynamical system " written in ACSL 1, circa 1982. INITIAL CINTERVAL CINT = 0.05 ALGORITHM IALG = 4 $ "RK3" CONSTANT X1IO = 0.0, X2IO=0.0, X1DIC=0.0, X2DIC = 0.0 CONSTANT M1 = 25.0, M2=2.0, DF=100.0, K2=5000 CONSTANT TDONE = 15.0 K1 = 1000.0 END $ "OF INITIALIZATION" DYNAMIC DERIVATIVE X3= STEP(0.0) X1D = INTEG((-DF/M1)*(X1D-X2D) - (K1/M1)*(X1-X2), X1DIC) X2D = INTEG((-DF/M1)*(X1D-X2D) - (K1/M1)*(X1-X2), ... (K2/M2)*(X2-X3*5.0), X2DIC) X1 = INTEG(X1D,X1IO) X2 = INTEG(X2D,X2IO) END "OF DERIVATIVE SECTION" TERMT(T .GE. TDONE) END "OF DYNAMIC SECTION" END "OF PROGRAM"
-- simple programming with floating-point #s with Ada.Float_Text_IO; use Ada.Float_Text_IO; procedure Think is A, B : Float := 0.0; -- A and B initially zero; note the period. I, J : Integer := 1; begin A := B * 7.0; I := J * 3; B := Float(I) / A; Put(B); end Think;
/* An Alef program to parse numbers out of * the string returned from /dev/time, and * print them from a separate proc. This is * a rather lame conglomeration of several * examples from Bob Flandrea's Alef * User's Guide */ tuple(int, uint, byte*) strtoui(byte* str, int base) { int val; while(*str != 0 && whitespace(*str)) str ; if(str == nil || *str == 0) return(0, 0, str); while(*str && !whitespace(*str)) { if(!validdigit(*str, base)) return (-1, val, str 1); /* extract digit into val */ str ; } return(1, val, str); } void receive(chan(uint) c) { int s; s = <-c; print("%d\n", s); if (s == 0) terminate(nil); } void main(void) { chan(uint) c; alloc c; proc receive(c); int ret; uint val; int fd; byte *p, buf[128], *newp; fd = open("/dev/time", OREAD|OCEXEC); if (fd >= 0) { read(fd, buf, sizeof(buf)); for(p = buf; *p; p = newp) { (ret, val, newp) = strtoui(p, 10); if(ret >= 0) c <-= val; if(ret == 0) break; } } }
// the main program, calculate the mean of // some numbers begin integer N; Read Int(N); begin real array Data[1:N]; real sum, avg; integer i; sum:=0; for i:=1 step 1 until N do begin real val; Read Real(val); Data[i]:=if val<0 then -val else val end; for i:=1 step 1 until N do sum:=sum Data[i]; avg:=sum/N; Print Real(avg) end end
Here is a better example, written in the
Algol60 publication language, from
Jean Sammet courtesy of
Glyn Webster.
procedure problem (a, b); value a, b; integer a, b; begin integer k; real e; for k := 2 × (a ÷ 2) 1 step 2 until b do begin e := if prime(k) then sqrt(3 × k sin(k)) else sqrt(4 × k cos(k)); if prime(k) then putlist(k, e, 'prime') else putlist(k, e, 'nonprime') end end problem;
-- Use the Finder to close all applications -- (by Joshua D. Baer) property specialApps : {"Finder"} tell application "Finder" set allApps to name of processes end tell repeat with someParticularApp in allApps if specialApps does not contain someParticularApp then tell application someParticularApp activate quit end tell end if end repeat
;; Very simple example of interactive extension ;; for AutoCAD (Defun c:SF2ACRE () (setq SF (getreal "Enter area in square feet: ")) (setq AGREAGE (/ SF 43560.0)) (alert (strcat "\nThe area in acres is " (rtos ARGEAGE 2 2))) )
BEGIN { if ("'$#argv'"==1) Col="'$1'"; else Col=1 } {Total = $Col; }; END { printf "Total for column %d with %d items: %d\n", Col,NR,Total }
{ Table data structure, adapted from an example in "Multiparadigm Data Structures in Leda" by Tim Budd, 1993 Assumes the list data structure is already defined. } class Association [X, Y : equality] of equality[Association]; var key : X; value : Y; function equals(argValue : Association[X, Y])->boolean; begin return key = argValue.key; end; end; class Table [X, Y : equality] { of equality[Association] }; var data : List[Association[X, Y]]; function add (newKey : X, newValue : Y); begin if ~ defined(data) then data := List[Association[X, Y]](); data.add(Association[X, Y](newKey, newValue)); end; function onEach (theFun : function(X, Y)); begin if defined(data) then data.onEach(function (item : Association[X, Y]); begin theFun(item.key, item.value); end); end; function items (byRef key : X, byRef value : Y)->relation; var element : Association[X, Y]; begin return defined(data) & data.items(element) & unify[X](key, element.key) & unify[Y](value, element.value); end; function includesKey (key : X)->boolean; var value : Y; begin if items(key, value) then return true; return false; end; function at (key : X)->Y; var value : Y; begin if items(key, value) then return value; return NIL; end; function atPut (key : X, value : Y); var element : Association[X, Y]; begin if defined(data) & data.items(element) & element.key = key then element.value := value else add(key, value); end; end;
global(sieve)? global(limit)? main :- write("N=?"), read_token(limit & int), next_prime(2), nl. remove_multiples(P,M) :- cond(M < limit, (sieve.M <-multiple_of(P),remove_multiples(P,M+P)) ). next_prime(P) :- P < limit, !, SP=sieve.P, ( SP=prime(P), !, write(P,' '), remove_multiples(P,2*P) ; succeed ), next_prime(P+1). next_prime(P).
# A simple program to sum up some numbers # presented on the command line, from # Bob Pike's forthcoming book on Limbo. implement Sum; include "sys.m"; sys: Sys; include "draw.m"; Sum: module { init: fn(context: ref Draw->Context, argl: list of string); }; init(context: ref Draw->Context, argl: list of string) { sys = load Sys Sys->PATH; argl = tl argl; # ignore command name if(len argl == 0){ sys->print("usage: sum numbers....\n"); return; } sum := 0.0; while(argl != nil){ arg := hd argl; sys->print("%s", arg); sum += real arg; argl = tl argl; if(argl != nil) sys->print(" + "); } sys->print(" = %g\n", sum); }
;; Simple factorial routine ;; (until I get a better example written) (defun fact1 (num) (cond ((not (integerp num)) nil) ((<= num 1) 1) (t (* num (fact1 (- num 1))))) )
; Recursive procedure to line, fractalized to DrawFractalLine :level :length ifelse :level < 1 [ fd :length] [ DrawFractalLine (sum -1 :level) (quotient :length 3.00) left 60 DrawFractalLine (sum -1 :level) (quotient :length 3.00) right 120 DrawFractalLine (sum -1 :level) (quotient :length 3.00) left 60 DrawFractalLine (sum -1 :level) (quotient :length 3.00) ] end ; procedure to clear screen and position turtle to SetupTurtle cs setpos [-160 -10] right 60 clean end ; setup turtle then draw Koch's snowflake(5) SetupTurtle setpensize [2 2] repeat 3 [DrawFractalLine 5 330 right 120]
' Find agents owned by the current user ' and remove them (Adapted from examples at ' www.lotus.com) Dim session As New NotesSession Dim db As NotesDatabase Dim agentArray(1 To 10) As NotesAgent Dim count as Integer Dim answer as string count = 0 Set db = session.CurrentDatabase Forall a In db.Agents If ( a.Owner = session.UserName ) Then Set agentArray(count) = a count = count + 1 If (count > 10) Then Exit Forall End If End If End Forall answer = Inputbox$( "You have " & count & " agents. Delete them?" ) If (answer = "y") Or (answer = "yes") Then Forall a in agentArray Call a.Remove End Foreall End If
-- Simple Lua program that implements the -- bisection method for solving non-linear equations function bisect(f,a,b,fa,fb) write(n," a=",a," fa=",fa," b=",b," fb=",fb,"\n") local c=(a+b)/2 if abs(a-b) < delta then return c end n=n+1 local fc=f(c) if fa*fc < 0 then return bisect(f,a,c,fa,fc) else return bisect(f,c,b,fc,fb) end end -- find root of f in the inverval [a,b]. -- bisection requires that f(a)*f(b) < 0 function solve(f,a,b) delta=1e-6 -- tolerance n=0 local z=bisect(f,a,b,f(a),f(b)) write(format("after %d steps, root is %.10g\n",n,z)) end -- test the bisection code with -- a function: x^3 - x - 1 function f(x) return x*x*x - x - 1 end solve(f,1,2)
h where h = 1 fby merge(merge(2 * h, 3 * h), 5 * h); merge(x,y) = if xx <= yy then xx else yy fi where xx = x upon xx <= yy; yy = y upon yy <= xx; end; end;
{ Sort program adapted from "Intermediate Pascal" } { by Joe Dorward. Illustrates arrays and types. } program sort_array(input,output); const max = 9; type integer_array = array[1..max] of integer; var I, J, K, swaps, temp : integer; test_array : integer_array; begin test_array[1] := 4; test_array[2] := 7; test_array[3] := 9; test_array[4] := 3; test_array[5] := 15; test_array[6] := 2; test_array[7] := 08; test_array[8] := 05; test_array[9] := 12; writeln(' *** Initial Array ***'); writeln(' --- --- --- --- --- --- --- --- --- '); for I := 1 to (max-1) do write('|',test_array[I]:2,' '); writeln('|',test_array[max]:2,' |'); for I := 1 to max do for J := (I 1) to max do { set J to start one ahead of I } if test_array[J] < test_array[I] then begin swaps := swaps 1; temp := test_array[J]; test_array[J] := test_array[I]; test_array[I] := temp; writeln; writeln('* * Condition After ',swaps:1,' swaps * *'); writeln(' --- --- --- --- --- --- --- --- --- '); for K := 1 to (max-1) do write('|',test_array[K]:2,' '); write('|',test_array[max]:2,' |'); end; writeln(' * Sorting Complete *'); end.
#!/usr/bin/perl # Simple program to extract column 3 from a file # and total up the numbers. $total = 0; sub sumcolumn { my $col = shift; my $lin = shift; my @fields; if ($lin) { @fields = split(/:/,$lin); $total = $fields[2]; } } while (<>) { sumcolumn(3,$_); } print "Total of column 3 is $total\n";
<?
mysql_connect("localhost","","") or die("Unable to connect to SQL server");
@mysql_select_db("php3") or die("Unable to select database");
$result = mysql_query("select * from customerTable limit 100");
?>
<table border="1">
<tr>
<?
while ($field=mysql_fetch_field($result)) {
echo "<th>";
echo "$field->name";
echo "</th>";
}
echo "</tr>";
while ($row = mysql_fetch_row($result)) {
echo "<tr>";
for ($i=0; $i<mysql_num_fields($result); $i ) {
echo "<td>";
echo "$row[$i]";
echo "</td>";
}
echo "</tr>\n";
}
echo "</table>";
The example below implements the Sieve of Erastosthenes (from the examples shipped with Pict 4.1).
now (reset checks) def interval (min:Int max:Int):(List Int) = if (>> min max) then nil else (cons min (interval (inc min) max)) def sieve (max:Int):(List Int) = ( def again (l:(List Int)):(List Int) = if (null l) then nil else (val n = (car l) if (>> (* n n) max) then l else (cons n (again (list.filter #Int l \(x) = (<> (mod x n) 0))))) (again (interval 2 max)) ) def prPrime (idx:Int x:Int):[] = if (== (mod idx 10) 9) then ((int.pr x); (nl)) else ((int.pr x); (pr " ")) (list.itApply (sieve 4000) prPrime);
// This program implements a fifo that can be used to send // data between two threads. (From the Pike 0.6 manual, sec 10) inherit Thread.Condition : r_cond; inherit Thread.Condition: w_cond; inherit Thread.Mutex: lock; mixed *buffer = allocate(128); int r_ptr, w_ptr; int query_messages() { return w_ptr - r_ptr; } // This function reads one mixed value from the fifo. // If no values are available it blocks until a write has been done. mixed read() { mixed tmp; object key=lock::lock(); while(!query_messages()) r_cond::wait(key); tmp=buffer[r_ptr % sizeof(buffer)]; w_cond::signal(); return tmp; } // This function pushes one mixed value on the fifo. // If the fifo is full it blocks until a value has been read. void write(mixed v) { object key=lock::lock(); while(query_messages() == sizeof(buffer)) w_cond::wait(key); buffer[w_ptr % sizeof(buffer)]=v; r_cond::signal(); }
R : An example for converting a number to english *LOOP T :ENTER A NUMBER, OR ZERO TO QUIT. C :$NUM= A :#Z E(Z=0) : U :*WRITNUM T :$NUM : J :*LOOP *WRITNUM U(Z<10) :*UNITS E(Z<10) : J(Z>999):*THOU J(Z>99) :*HUND J(Z>19) :*TWENTY C(Z=10) :$NUM=$NUM TEN C(Z=11) :$NUM=$NUM ELEVEN C(Z=12) :$NUM=$NUM TWELVE C(Z=13) :$NUM=$NUM THIRTEEN C(Z=14) :$NUM=$NUM FOURTEEN C(Z=15) :$NUM=$NUM FIFTEEN C(Z=16) :$NUM=$NUM SIXTEEN C(Z=17) :$NUM=$NUM SEVENTEEN C(Z=18) :$NUM=$NUM EIGHTEEN C(Z=19) :$NUM=$NUM NINETEEN E: *UNITS C(Z=1) :$NUM=$NUM ONE C(Z=2) :$NUM=$NUM TWO C(Z=3) :$NUM=$NUM THREE C(Z=4) :$NUM=$NUM FOUR C(Z=5) :$NUM=$NUM FIVE C(Z=6) :$NUM=$NUM SIX C(Z=7) :$NUM=$NUM SEVEN C(Z=8) :$NUM=$NUM EIGHT C(Z=9) :$NUM=$NUM NINE E: *TWENTY C:Y=Z%10 C:Z=Z-Y C(Z=20) :$NUM=$NUM TWENTY C(Z=30) :$NUM=$NUM THIRTY C(Z=40) :$NUM=$NUM FORTY C(Z=50) :$NUM=$NUM FIFTY C(Z=60) :$NUM=$NUM SIXTY C(Z=70) :$NUM=$NUM SEVENTY C(Z=80) :$NUM=$NUM EIGHTY C(Z=90) :$NUM=$NUM NINETY C:Z=Y E(Z=0) : J:*WRITNUM *HUND C :Y=Z%100 C :Z=(Z-Y)/100 U :*UNITS C :$NUM=$NUM HUNDRED C :Z=Y E(Z=0) : J :*WRITNUM *THOU C :X=Z%1000 C :Z=(Z-X)/1000 U :*WRITNUM C :$NUM=$NUM THOUSAND C :Z=X E(Z=0) : J :*HUND
FINDSTRINGS: PROCEDURE OPTIONS(MAIN) /* READ A STRING, THEN PRINT EVERY */ /* SUBSEQUENT LINE WITH A MATCH */ DECLARE PAT VARYING CHARACTER(100), LINEBUF VARYING CHARACTER(100), (LINENO, NDFILE, IX) FIXED BINARY; NDFILE = 0; ON ENDFILE(SYSIN) NDFILE=1; GET EDIT(PAT) (A); LINENO = 1; DO WHILE (NDFILE=0); GET EDIT(LINEBUF) (A); IF LENGTH(LINEBUF) > 0 THEN DO; IX = INDEX(LINEBUF, PAT); IF IX > 0 THEN DO; PUT SKIP EDIT (LINENO,LINEBUF)(F(2),A) END; END; LINENO = LINENO 1; END; END FINDSTRINGS;
%!PS-Adobe-2.0 % Draw a string at an angle at a point /printat { % str x y angle => - gsave 4 1 roll translate exch rotate 0 0 moveto show grestore } def % find the center of the page /pagecenter { % - => cx cy clippath pathbbox 4 1 roll exch sub 2. div 3 1 roll sub 2. div } def % set up font and constants /Times-Bold findfont 36 scalefont setfont pagecenter /cy exch def /cx exch def /steps 9 def /basegray 0.75 def /incrgray basegray steps div def /baseangle 360 steps div def /incrangle 360 steps div def % draw a string as a rosette steps { basegray setgray (PostScript) cx cy baseangle printat /basegray basegray incrgray sub def /baseangle baseangle incrangle add def } repeat % done with this page showpage
% Quicksort in Prolog, by Keesey adapted from Bratko gtq(X,Y) :- X @> Y. quicksort( [],[] ). quicksort( [X | Tail], Sorted) :- split( X, Tail, Small, Big), quicksort( Small, SortedSmall), quicksort( Big, SortedBig), conc( SortedSmall, [X | SortedBig], Sorted). split( _, [], [], []). split( X,[Y | Tail], [Y | Small], Big) :- gtq( X, Y),!, split( X, Tail, Small, Big). split( X, [Y | Tail], Small, [Y | Big] ) :- split( X, Tail, Small, Big). conc([],L,L). conc( [X | L1], L2, [X | L3]) :- conc( L1, L2, L3).
# standard binary search tree from # a tree data structure package by Dan Stubbs # class binary_tree: def __init__ (self): self.tree = None def insert (self, key): if self.tree: self._insert (self.tree, key) else: self.tree = node(key) def _insert (self, tree, key): if key < tree.key: if tree.left: self._insert (tree.left, key) else: tree.left = node(key) else: if tree.right: self._insert (tree.right, key) else: tree.right = node(key)
-- Stable quicksort in Haskell by Lennart Augustsson -- module QSort(sortLe, sort) where sortLe :: (a -> a -> Bool) -> [a] -> [a] sortLe le l = qsort le l [] sort :: (Ord a) => [a] -> [a] sort l = qsort (<=) l [] -- qsort is stable and does not concatenate. qsort le [] r = r qsort le [x] r = x:r qsort le (x:xs) r = qpart le x xs [] [] r -- qpart partitions and sorts the sublists qpart le x [] rlt rge r = -- rlt and rge are in reverse order and must be sorted with an -- anti-stable sorting rqsort le rlt (x:rqsort le rge r) qpart le x (y:ys) rlt rge r = if le x y then qpart le x ys rlt (y:rge) r else qpart le x ys (y:rlt) rge r
use lists, functions, products; type rose_tree alpha == alpha # list(rose_tree alpha); dec bf_list : rose_tree alpha -> list alpha; --- bf_list t <= [t]. iterate (concat o map snd). front_with (/= []). concat. map fst;
HOW TO RETURN index doc: PUT {} IN where FOR line.no IN keys doc: TREAT LINE RETURN where TREAT LINE: FOR word IN split doc[line.no]: IF word not.in keys where: PUT {} IN where[word] INSERT line.no IN where[word]
PROGRAM ONE WHEEL " Simple model of a dynamical system " written in ACSL 1, circa 1982. INITIAL CINTERVAL CINT = 0.05 ALGORITHM IALG = 4 $ "RK3" CONSTANT X1IO = 0.0, X2IO=0.0, X1DIC=0.0, X2DIC = 0.0 CONSTANT M1 = 25.0, M2=2.0, DF=100.0, K2=5000 CONSTANT TDONE = 15.0 K1 = 1000.0 END $ "OF INITIALIZATION" DYNAMIC DERIVATIVE X3= STEP(0.0) X1D = INTEG((-DF/M1)*(X1D-X2D) - (K1/M1)*(X1-X2), X1DIC) X2D = INTEG((-DF/M1)*(X1D-X2D) - (K1/M1)*(X1-X2), ... (K2/M2)*(X2-X3*5.0), X2DIC) X1 = INTEG(X1D,X1IO) X2 = INTEG(X2D,X2IO) END "OF DERIVATIVE SECTION" TERMT(T .GE. TDONE) END "OF DYNAMIC SECTION" END "OF PROGRAM"
-- simple programming with floating-point #s with Ada.Float_Text_IO; use Ada.Float_Text_IO; procedure Think is A, B : Float := 0.0; -- A and B initially zero; note the period. I, J : Integer := 1; begin A := B * 7.0; I := J * 3; B := Float(I) / A; Put(B); end Think;
/* An Alef program to parse numbers out of * the string returned from /dev/time, and * print them from a separate proc. This is * a rather lame conglomeration of several * examples from Bob Flandrea's Alef * User's Guide */ tuple(int, uint, byte*) strtoui(byte* str, int base) { int val; while(*str != 0 && whitespace(*str)) str ; if(str == nil || *str == 0) return(0, 0, str); while(*str && !whitespace(*str)) { if(!validdigit(*str, base)) return (-1, val, str 1); /* extract digit into val */ str ; } return(1, val, str); } void receive(chan(uint) c) { int s; s = <-c; print("%d\n", s); if (s == 0) terminate(nil); } void main(void) { chan(uint) c; alloc c; proc receive(c); int ret; uint val; int fd; byte *p, buf[128], *newp; fd = open("/dev/time", OREAD|OCEXEC); if (fd >= 0) { read(fd, buf, sizeof(buf)); for(p = buf; *p; p = newp) { (ret, val, newp) = strtoui(p, 10); if(ret >= 0) c <-= val; if(ret == 0) break; } } }
// the main program, calculate the mean of // some numbers begin integer N; Read Int(N); begin real array Data[1:N]; real sum, avg; integer i; sum:=0; for i:=1 step 1 until N do begin real val; Read Real(val); Data[i]:=if val<0 then -val else val end; for i:=1 step 1 until N do sum:=sum Data[i]; avg:=sum/N; Print Real(avg) end end
Here is a better example, written in the
Algol60 publication language, from
Jean Sammet courtesy of
Glyn Webster.
procedure problem (a, b); value a, b; integer a, b; begin integer k; real e; for k := 2 × (a ÷ 2) 1 step 2 until b do begin e := if prime(k) then sqrt(3 × k sin(k)) else sqrt(4 × k cos(k)); if prime(k) then putlist(k, e, 'prime') else putlist(k, e, 'nonprime') end end problem;
-- Use the Finder to close all applications -- (by Joshua D. Baer) property specialApps : {"Finder"} tell application "Finder" set allApps to name of processes end tell repeat with someParticularApp in allApps if specialApps does not contain someParticularApp then tell application someParticularApp activate quit end tell end if end repeat
;; Very simple example of interactive extension ;; for AutoCAD (Defun c:SF2ACRE () (setq SF (getreal "Enter area in square feet: ")) (setq AGREAGE (/ SF 43560.0)) (alert (strcat "\nThe area in acres is " (rtos ARGEAGE 2 2))) )
BEGIN { if ("'$#argv'"==1) Col="'$1'"; else Col=1 } {Total = $Col; }; END { printf "Total for column %d with %d items: %d\n", Col,NR,Total }
#include <stdio.h> /* count lines of standard input */ main(int argc, char *argv[]) { char lbuf[256]; int lcnt; for(lcnt = 0; fgets(lbuf,sizeof(lbuf) - 1, stdin); cnt ); printf("%d lines\n", lcnt); exit(0); }
// Adapted from the paper "The C* Parallel // Programming Language" by Andrews and Barszcz, 1992. // Skyline Matrix Problem solution #define N 4 #define BIG 1024 domain Matrix { float a; int i; int j; } A[N][N]; domain RHS { float b; int i; } B[N]; domain Skyline { float s; int i; int j; } SKY[BIG]; domain Vector { float element; int start; } I[N], J[N]; void main() { int k,l,m; float x[N], element; float rowsum, pivot; int NonZeros; readMatrix(); [domain RHS].{ i = (int)(this - &B[0]); } [domain Matrix].{ int offset = (int) (this - &A[0][0]); i = offset / N; j = offset % N; } for(k = 0; k<N; k ) { rowsum = 0; [domain Matrix].{ if (i == k) rowsum = a; } B[k].b = rowsum; } NonZeros = map(); /* put matrix in skyline form? */ for(k=0; k<(N-1); k ) { [domain Skyline].{ if ((i ==k) && (j==k)) Pivot ,= s; if (((i>k) && (j==k)) && (I[i].start <= k)) { s = s / Pivot; I[i].element = s; } if (((i==k) && (j > k)) && (J[j].start <= k)) J[j].element = s; if (((i > k) && (j > k)) && ((I[i].start <= k) && J[j].start <= k)) s = s - (I[i].element * J[j].element); } } for(k = (N-1); k > 0; k--) { [domain Skyline].{ if (((i <= k) && (j ==k)) && (J[k].start <= k)) J[j].element = s; } x[k] ,= B[k].b / J[j].element; [domain Skyline].{ if ((i < k) && (J[k].start < k)) b = b - (J[j].element * x[k]); } } [domain Skyline].{ if (i == 0 && j == 0) Pivot ,= s; } x[0] = B[0].b / Pivot; printf("x\n"); for(k = 0; k<N; k ) printf("%f\n",x[k]); }
// This is just a placehold until I write a // better example. #include <iostream.h> #include <String.h> main(int argc, char *argv[]) { String *s1; s1 = new String("Hello World!"); cout << *s1 << endl << "Length is:" << s1->length() << endl; }
-- Adapted from Cecil Project v2.0 distribution tests method copy_file_using_streams(name1@:string, name2@:string):void { let f1:unix_file := open_file(name1, open_for_reading); let f2:unix_file := open_file(name2, create_for_writing); (name1 || " is " || if(f1.is_unreadable, {"not "}, {""}) || "readable"). print_line; (name2 || " is " || if(f2.is_unreadable, {"not "}, {""}) || "readable"). print_line; while({ f1.before_end }, { f2.next := f1.next; }); close(f1); close(f2); } let var name1 := ask("Name of input file: "); let var name2 := ask("Name of output file: "); print("Copying using streams..."); copy_file_using_streams(name1, name2); print_line(" done.");
<CFSWITCH EXPRESSION="#ThisTag.ExecutionMode#"> <CFCASE VALUE="start"> <CFIF StructIsEmpty(attributes.EMPINFO)> <CFOUTPUT>Error. No employee data was passed.</CFOUTPUT> <CFEXIT METHOD="ExitTag"> <CFELSE> <!--- Add the employee ---> <CFQUERY NAME="AddEmployee" DATASOURCE="cfsnippets"> INSERT INTO Employees (FirstName, LastName, Email, Phone, Department) VALUES <CFOUTPUT> ( #StructFind(attributes.EMPINFO, "firstname")# , #StructFind(attributes.EMPINFO, "lastname")# , #StructFind(attributes.EMPINFO, "email")# , #StructFind(attributes.EMPINFO, "phone")# , #StructFind(attributes.EMPINFO, "department")# ) </CFOUTPUT> </CFQUERY> </CFIF> <CFOUTPUT><HR>Employee Add Complete</CFOUTPUT> </CFCASE> </CFSWITCH>
-- still looking for a good code example
#include <cilk.h>
#include <stdlib.h>
#include <stdio.h>
cilk int fib(int n)
{
if (n < 2)
return (n);
else {
int x, y;
x = spawn fib(n - 1);
y = spawn fib(n - 2);
sync;
return (x y);
}
}
cilk int main(int argc, char *argv[])
{
int n, result;
n=atoi(argv[1]);
result=spawn fib(n);
sync;
printf("Result: %d\n", result);
return 0;
}
// Very simple Fibonnacci example adapted from v2.1 // "Introduction to the CLAIRE Programming Language" begin(fib_module) fib[n:(0..10)] : integer := (if (n < 2) 1 else fib[n - 1] fib[n - 2]) test() -> (for i in (0 .. 10) printf("fib(~S) = ~S\n",i,fib[i]) end(fib_module)
% Driver and function to compute factorials % from the PCLU distribution. start_up = proc () pi: stream := stream$primary_input() po: stream := stream$primary_output() while true do stream$puts(po, "Enter an integer (or RETURN to exit): ") s: string := stream$getl(pi) if string$empty(s) then break end n: int := int$parse(s) except when bad_format: stream$putl(po, "Illegal integer") end stream$putl(po, int$unparse(n) || "! = " || int$unparse(factorial(n))) except when negative: stream$putl(po, "Integer must be positive") when overflow: stream$putl(po, "Overflow") end end end start_up factorial = proc (n: int) returns (int) signals (negative, overflow) if n < 0 then signal negative end if n = 0 then return(1) end return(n*factorial(n-1)) resignal overflow end factorial
Insufficient documentation for producing a reasonable example.
IDENTIFICATION DIVISION PROGRAM-ID. SUM-OF-PRICES. AUTHOR. TERENCE-PRATT. SOURCE. PROGRAMMING-LANGUAGES-2ND-EDITION-1984 ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT INP-DATA ASSIGN TO INPUT. SELECT RESULT-FILE ASSIGN TO OUTPUT. DATA DIVISION. FILE SECTION. FD INP-DATA LABEL RECORD IS OMITTED. 01 ITEM-PRICE 02 ITEM PICTURE X(30). 02 PRICE PICTURE 9999V99. 02 FILLER PICTURE X(44). FD RESULT-FILE LABEL RECORD IS OMITTED. 01 RESULT-LINE PICTURE X(132). WORKING-STORAGE SECTION. 77 TOT PICTURE 999999V99, VALUE 0, USAGE IS COMPUTATIONAL. 77 COUNT PCITURE 9999, VALUE 0, USAGE IS COMPUTATIONAL. 01 SUM-LINE. 02 FILLER VALUE ' SUM ='PICTURE X(12). 02 SUM-OUT PICTURE $$,$$$,$$9.99. 02 FILLER VALUE ' NO. OF ITEMS ='PICTURE X(21). 02 COUNT-OUT PICTURE ZZZ9.99. 01 ITEM-LINE. 02 ITEM-OUT PICTURE X(30). 02 PRICE-OUT PICTURE ZZZ9.99. PROCEDURE DIVISION. START. OPEN INPUT INP-DATA AND OUTPUT RESULT-FILE. READ-DATA. READ INP-DATA AT END GO TO PRINT-LINE. ADD PRICE TO TOT. ADD 1 TO COUNT. MOVE PRICE TO PRICE-OUT. MOVE ITEM TO ITEM-OUT. WRITE RESULT-LINE FROM ITEM-LINE. GO TO READ-DATA. PRINT-LINE. MOVE TOT TO SUM-OUT. MOVE COUNT TO COUNT-OUT. WRITE RESULT-LINE FROM SUM-LINE. CLOSE INP-DATA AND RESULT-FILE. STOP RUN.
;; An example of array search from the common ;; lisp standard (defun finder (obj vec start end) (let ((range (- end start))) (if (zerop range) (if (eql obj (aref vec start)) obj nil) (let ((mid ( start (round (/ range 2))))) (let ((obj2 (aref vec mid))) (if (< obj obj2) (finder obj vec start (- mid 1)) (if (> obj obj2) (finder obj vec ( mid 1) end) obj)))))))
// Solution to Hamming's problem in Clean, // generate an infinite sorted stream of numbers // of the form (2^n)*(3^m)*(5*p). From the examples // distributed with Concurrent Clean v1.2. Ham::[Int] Ham = y where y = [1:merge (merge (map ((*) 2) y) (map ((*) 3) y)) (map ((*) 5) y)] merge [] [] = [] merge f [] = f merge [] f = f merge f=:[a:b] g=:[c:d] | a<c = [a:merge b g] | a==c = merge f d | otherwise = [c: merge f d] Start::[Int] Start = take NrElements Ham NrElements :== 300 // Size of finite sample to take.
{ A small example monitor and process from Hansen's 1993 } { paper given at HOPL-II. } type linebuffer = monitor var contents : line; full : Boolean; sender, receiver : queue; procedure entry receive(var text : line); begin if not full then delay(receiver); text := contents; full := false; continue(sender); end; procedure entry send(text : line); begin if full then delay(sender); contents := text; full := true; continue(receiver); end; begin full := false; end; { linebuffer } type printerprocess = process(buffer: linebuffer) var param : ioparam; text : line; begin param.operation := output; cycle buffer.receive(text); repeat io(text,param,printdevice) until param.status = complete; end end;
WITHOBJECT "CorelPhotoPaint.Automation.7" .SetDocumentInfo 96, 96 .MaskSelectAll .EditCopy .ImagePapersize 192, 96, 0, 0, 5, 255, 255, 255, 0 .MaskInvert .EditPasteIntoSelection .MaskChannelAdd "Alpha 1" .MaskBorder 4, 1 .ImageBCI -20, 0, 0 .EndColorEffect .MaskChannelToMask 0, 0 offset% = 50 BEGIN DIALOG Dialog4 182, 79, "Corel SCRIPT Dialog" SPINCONTROL 91, 12, 76, 18, offset% TEXT 28, 17, 55, 11, "Offset amount:" OKBUTTON 56, 50, 69, 21 END DIALOG X = Dialog(Dialog4) .EffectOffset 0, offset%, TRUE, 0 .MaskRemove END WITHOBJECT
#!/bin/csh # A simple csh script to find a command on # the directories listed in the environment # variable PATH, and print out information # about it. set cmd=$1 if ("$cmd" == "") then echo "Usage: findcmd commandname" exit 1 endif set cnt=0 foreach dir ($path) set check="$dir/$cmd" if (-x "$check" && ! (-d "$check")) then file $check ls -ldg $check set cnt=$cnt 1 endif end if ($cnt == 0) then echo "Sorry, command $cmd not found." exit 1 else exit 0 endif
PHIL = *[ ...During n'th lifetime THINK; room!enter( ); fork(i)!pickup( ); fork((i 1) mod 5)!pickup; EAT; fork(i)!putdown( ); fork((i 1) mod 5)!putdown( ); room!exit( ); ] FORK = *[ phil(i)?pickup( ) -> phil(i)?putdown( ); [] phil((i - 1) mod 5)?pickup( ) -> phil((i - 1) mod 5)?putdown( ); ROOM = occupancy:integer; occupancy = 0; *[(i:0..4)phil(i)?enter( ) -> occupancy := occupancy 1; [] (i:0..4)phil(i)?exit( ) -> occupancy := occupancy - 1; MAIN = [room::ROOM || fork(i:0..4)::FORK || phil(i:0..4)::PHIL].
* A subroutine to draw 1-d chaos, from a * sample program by Bruce Sherwood. unit chaos f: pop, rate $$ population and growth rate i: n, TRIES=40, base=8 i: usecolor f: h, s, v calc usecolor := (zncolors >= 8 base) palette zred,100,0,0,zwhite if usecolor loop n := 0,7 $$ make hues from blue to red getrgb 240[1-(n 1)/8],100,100; h, s, v palette base n,h,s,v endloop endif color zwhite do graph color zred loop rate := 2.7, 3.99, .01 calc pop := .1 $$ starting population loop n := 1, TRIES * New population is rate times current population * times a resource-limiting factor (1-pop): calc pop := rate*pop*(1-pop) if usecolor color base int(8(n-1)/TRIES) elseif TRIES-n > 8 reloop endif gfill rate,pop;rate .01,pop .005 endloop endloop
The syntax of Curry is complex, compact, and similar to that of Haskell. Each statement of a Curry program is an equation or predicate. Executing a Curry program consists of simplifying equations and expressions until a particular specified goal is reached or a particular solution is obtained. Primitive data types supported by Curry include booleans, integers, reals, chars, and strings. Aggregate and specialized data types include tuples, lists, functions, and constraints. Oddly enough, Curry uses the same comment syntax as Ada. The module construct serves to encapsulate libraries of functions, data types, and expressions. The module seems to be the only program structuring facility in Curry.
Like many functional languages, Curry supports a declarative I/O model. This kind of model basically represents input and output operations as expressions involving 'the World'.
Some of the advanced features of Curry are listed below.
As an academic project, implementations of Curry are available free. Documentation is available on the web, but almost exclusively in DVI format.
Several implementations of Curry exist. The most viable one seems to be PACS, the Portland Aachen Curry System. It is a compiler that translates Curry programs into various intermediate forms: Prolog or Java. Free downloads of PACS for UNIX systems are available from RWTH Aachen. Other Curry implementations are interpreters written in Prolog.
There has been a trend in the 1990s to try to integrate ideas from some of the most powerful computer programming research paradigms. Curry, like LEDA and NIAL, is an example of this trend.
-- quicksort using higher-order functions: -- filter elements in a list (predefined as `filter'): filter_ :: (a -> Bool) -> [a] -> [a]; filter_ _ [] = [] filter_ p (x:xs) = if p x then x : filter_ p xs else filter_ p xs qsort :: [Int] -> [Int] qsort [] = [] qsort (x:l) = qsort (filter (< x) l) x : qsort (filter (>= x) l)
Descriptions in this dictionary are ©1997-99 Neal Ziring. Some examples copyright of their respective authors. Some technologies and languages are trademarked. Permission to copy descriptions is granted as long as authorship credit is preserved.
Comments on this dictionary, corrections and suggestions, are all welcome. Please use email, the address is ziring@home.com
[Ziring MicroWeb Home] [Dictionary Start] [Sign Guestbook]
Dictionary and script maintained by Neal Ziring, last major modifications 3/18/98. Most recent additions to dictionary and master list, 1/00.