/ doc / krc.txt
krc.txt
  1  KRC(1)			    General Commands Manual			KRC(1)
  2  
  3  
  4  
  5  NAME
  6         krc - Kent Recursive Calculator
  7  
  8  SYNOPSIS
  9         krc [options] [file] [arguments] ...
 10  
 11  OPTIONS
 12         -h cells
 13  	      Specify  the  size of the heap.  On a 32-bit computer, each cell
 14  	      requires 16 bytes, on a 64-bit computer 32 bytes.   The  default
 15  	      is 128000 cells.
 16  
 17         -d bytes
 18  	      Specify  the  size of the dictionary, or "string space", used to
 19  	      store identifiers, comments and strings.	The default  is  64000
 20  	      bytes.
 21  
 22         -n     Don't include the prelude of standard definitions.
 23  
 24         -l lib Use lib in place of the prelude.
 25  
 26         -L     Use a legacy prelude from 1981 in place of the prelude.
 27  
 28         -s     Load prelude or lib stripped of comments (saves string space).
 29  
 30         -c     Turn on reduction counting (the same as the /count command).
 31  
 32         -g     Turn  on	garbage collector statistics (the same as the /gc com-
 33  	      mand).
 34  
 35         -o     Turn on the printing  of	compiled  objects  (the  same  as  the
 36  	      /object command).
 37  
 38         -z     Sets base for list indexing to 1 instead of 0 (legacy option).
 39  
 40         -e expression[?!]
 41  	      Instead  of  being  interactive, evaluate expression and display
 42  	      its value (with `?') or flat-print the value (with `!').
 43  
 44         If a file name is given after the options, its contents will be	loaded
 45         as  the	current  script.   If  you  don't give a file name the current
 46         script is initially empty.
 47  
 48         Arguments following the file are permitted only when  a	-e  option  is
 49         present	and in this case the file name and any arguments are placed in
 50         a list of strings called "argv".
 51  
 52  DESCRIPTION
 53         Kent Recursive Calculator was one of the earliest  higher-order,  lazy,
 54         purely  functional  programming	systems. Written around 1980, it was a
 55         simplified version of its  author's  language  SASL,  developed	at  St
 56         Andrews University in 1972-6, and in turn was succeeded by Miranda, the
 57         main precursor of Haskell. These days it has the advantages of being  a
 58         simple  language  of this kind capable of running in very little memory
 59         (75KB code plus whatever space is allocated for heap and dictionary).
 60  
 61         A KRC program is called a script, which consists of a sequence of defi-
 62         nitions	each  of which consists of an optional comment followed by one
 63         or more equations, one per line.
 64  
 65         When you invoke krc, it loads a set of standard definitions called  the
 66         prelude, then prints a welcome message followed by a prompt, krc>.  You
 67         have now entered a KRC session.	In a session you  can  type  commands,
 68         expressions  to be evaluated, and definitions to be entered in the cur-
 69         rent script.  A new prompt appears as each task is completed, until you
 70         end the session.
 71  
 72  COMMANDS
 73         The  interpreter accepts a range of commands to inspect, edit, load and
 74         save scripts, as well as a few system-oriented things.  Each command is
 75         entered on a single line, followed by [Enter].
 76  
 77         The  command to inspect a definition, say of `foo', is just the name on
 78         a line by itself
 79  	   foo
 80         the system responds by displaying the definition associated with `foo',
 81         which  may  be in the prelude or in the current script.	If the defini-
 82         tion has more than one equation these are shown numbered, from  1,  the
 83         numbers are used when editing definitions.
 84  
 85         You  can  display  a  section of the script, say from the definition of
 86         `foo' to `bar' by typing
 87  	   foo .. bar
 88  
 89         The other commands all start with a / character.
 90  
 91         /      Displays all of the current script
 92  
 93         /quit  Ends a KRC session. Shorthand: /q.  Typing  control-D  also  has
 94  	      this effect.
 95  
 96         Be  aware that ending a session does not automatically save the current
 97         script, for that you must use /save (see below).
 98  
 99         In the commands which follow `name' means one of the names  defined  in
100         the current script;
101  
102         Where  it says `name(s)' you can put a name, several names separated by
103         spaces, or a range foo..bar which refers to definitions foo through bar
104         of  the current script, or foo.. which means from the definition of foo
105         to the end of the script.
106  
107         Where it says `part(s)', this refers to equation numbers from a defini-
108         tion in the script, for deletion or reordering.
109  
110         A part can be a single number like 1, a range like 2..4, something like
111         4.., which means from equation 4 to the end of the definition;  part(s)
112         means a list of these separated by spaces.
113  
114         /delete name(s)
115  	      Deletes one or more definitions from the script.	Shorthand: /d
116  	      If no names are supplied, it deletes the whole script (beware!).
117  
118         /delete name part(s)
119  	      Deletes  the numbered equations from the definition of name.  To
120  	      delete the comment, enter an empty comment for  the  same  name,
121  	      for example "foo:-;"
122  
123         /reorder name name(s)
124  	      Place  the  definitions  of  one or more names immediately after
125  	      those for the first mentioned name, in the order shown.
126  
127         /reorder name part(s)
128  	      Reorder the equations within a definition by moving the numbered
129  	      equations listed in part(s) to the top of the definition, in the
130  	      order shown.
131  
132         /aborder
133  	      Sorts the script's definitions into alphabetical order.
134  
135         /rename from,to
136  	      Change the name `from' into `to', in all the places where it  is
137  	      used in the script; from and to can both be lists of names sepa-
138  	      rated by spaces, in which case the first name in from is changed
139  	      to  the  first name in to and so on. This allows you to swap two
140  	      or more names in the script without losing any of them.
141  
142         /save filename
143  	      Saves the script in the named file.  If filename is omitted,  it
144  	      saves to the last filename mentioned.
145  
146         /get filename
147  	      Adds the contents of a file to the script.  If filename is omit-
148  	      ted, from the last filename mentioned.
149  
150         /file  Shows the current default filename. Shorthand: /f
151  
152         /file filename
153  	      Changes the default filename.
154  
155         /list filename
156  	      Lists the contents of a disk file, like Unix's  "cat"  or  DOS's
157  	      "type"  commands.  If the filename is omitted, it reads from the
158  	      last filename mentioned.
159  
160         /dir   List the filenames in the  current  directory  or  folder,  like
161  	      Unix's "ls" or DOS's "dir" commands.
162  
163         /names Displays the names defined in the script.
164  
165         /lib   Displays the names defined in the prelude.
166  
167         /openlib
168  	      Allows  you  to  modify the definitions of the prelude (they are
169  	      normally write-protected).  Any changes are made to the copy  of
170  	      the  definitions held in memory during the session - only if you
171  	      use /save (filename) do they get written to a file.
172  
173         /clear Clear all memo fields.  When a simple definition in  the	script
174  	      is  expanded i.e. one like foo = STUFF, the value is stored in a
175  	      memo field for foo so STUFF need not be evaluated  again.  These
176  	      are  cleared  automatically when any definition in the script is
177  	      changed.
178  
179         /count Turns on reduction counting.
180  
181         /gc    Enables the printing of memory usage  information  each  time  a
182  	      garbage collection happens.
183  
184         /reset Turns off reduction counting, garbage collection information and
185  	      object display (see below).
186  
187         /dic   Report current state of string space.
188  
189         /help  Prints a list of help topics. Shorthand: /h
190  
191         /help topic
192  	      Displays the relevant helpfile, using the UNIX  command  `less'.
193  	      This allows you to move backwards (type `b') in the file as well
194  	      as forwards (type SPACE, or ENTER to move forward one line at  a
195  	      time),  type  `q' to quit.  Say `man 1 less' on the UNIX command
196  	      line for more details.
197  
198         These last commands are for use in debugging the system:
199  
200         /object
201  	      Displays the internal representation of each  expression	before
202  	      evaluating it.
203  
204         /lpm   The  "List  Post	Mortem"  displays  the	KRC machine's internal
205  	      state.
206  
207  EXPRESSION EVALUATION
208         An expression is a mathematical formula denoting a value.  For  details
209         of  what  can be in an expression see later sections: IDENTIFIERS, DATA
210         TYPES, OPERATORS and ZF EXPRESSIONS.  To evaluate an  expression  in  a
211         KRC  session  and  print  the result on the screen, type the expression
212         followed by `?'.
213  
214         For example, you could type 2+2? to obtain 4.
215  
216         If the value is a data structure it is printed as you would  enter  it,
217         with  quote marks around strings, square brackets around lists and com-
218         mas between list elements.  For example (`++' joins lists together):
219  
220  	   krc> [1..3]++["...\n"]++[2*2]?
221  
222  	   [1,2,3,"...\n",4]
223  
224         Note that with `?' control characters in a string are shown, not obeyed
225         ("\n" means newline).
226  
227         An alternative method of printing uses `!' in place of `?'.
228  
229  	   krc> [1,2,3,"...\n",4]!
230  
231  	   123...
232  	   4
233  
234         `!' prints strings without quotes, obeying any control characters, num-
235         bers are printed in the usual way and with  lists  `!'  scans  left  to
236         right, recursively scanning any sublists encountered, printing only the
237         atoms (numbers and strings).   The  effect  is  as  if  the  data  were
238         squashed flat and joined up into a single string (although `!' does not
239         actually use any additional string space).
240  
241         As a general guide `?' (print values to show structure)	is  used  when
242         developing  and	testing  functions  and `!' (flat-print) for the final
243         output of a program where you want to control layout.   Note  that  `?'
244         adds a trailing newline while `!' doesn't.
245  
246         The  reader  may  find it helpful to study the function show defined in
247         the prelude;
248  	      x?
249         is actually equivalent to show x : ["\n"]!
250  
251         Reminder: For KRC to print the value of an expression it must  be  fol-
252         lowed by `?' or `!'.
253  
254  THE SCRIPT: COMMENTS AND EQUATIONS
255         A  KRC  script  consists of a sequence of definitions, each of which is
256         composed of an optional comment followed by one or more equations.  The
257         order  of  the definitions has no significance as they are all in scope
258         throughout the script, but the order of the equations within a  defini-
259         tion may affect its meaning, as they are tried in the order written.
260  
261         A  comment  is  the name, of a function or other data item, followed by
262         the two characters ":-" followed by any number of  lines  of  text  and
263         terminated by the first semicolon ";".
264  	   flub :- here is some text
265  		   ... explaining "flub";
266  
267         An equation is one line of a definition and has this form:
268  	      LHS = expression
269         or
270  	      LHS = expression, guard
271         where  LHS  ("left  hand side") is a name optionally followed by formal
272         parameters and expression describes the value which the lhs assumes  in
273         this case.
274  
275         The  optional  guard  is a Boolean (i.e. truth-valued) expression which
276         determines if the equation is applicable. If  the  guard  evaluates  to
277         "TRUE" the equation is used, otherwise it is not.
278  
279         Note that equations are written one per line (no terminating semicolons
280         needed, or allowed).  Examples
281  	      radix = 10
282  	      girls = ["susan","jill","pandora"]
283         are simple definitions.	A simple definition has just  a  name  as  its
284         LHS.
285  
286         We can define a function by introducing a formal parameter
287  	      sq n = n * n
288         The formal parameter `n' is a local variable of the equation.  Any name
289         can be used as a formal parameter, it does not have to be a single let-
290         ter.   However name clashes, like using `sq' as a formal parameter when
291         it is also a top-level name, are best avoided (occurences of  the  name
292         on the right of the equation will refer to the formal parameter).
293  
294         Names  which  appear  at  the  head  of an LHS, which to this point are
295         `radix', `girls' and `sq', are known as top-level names	and  have  the
296         whole  script  as  their scope, as do the names defined in the prelude.
297         (The scope of a name is the region of text in which it can be used with
298         the same meaning.)
299  
300         Here is a function of two parameters
301  	      sqdiff m n = m*m - n*n
302         We call it by writing e.g.
303  	      sqdiff 2 3
304         not sqdiff(2,3) as you would in some other programming languages.
305  
306         More  complex  function	definitions may require several equations, for
307         example
308  	      fac 0 = 1
309  	      fac n = n * fac(n-1)
310         defines a factorial function which can then be  used,  for  example  by
311         writing
312  	      fac 10?
313         Note  the  use of a constant, 0, as formal parameter in the first equa-
314         tion.  This is one way to do case analysis.
315  
316         Guards can also be used to do case analysis.  A safer version of  `fac'
317         would be:
318  	      fac n = 1, n <= 0
319  		    = n * fac(n-1)
320         Here we use a guard, `n <= 0', to stop `fac' going into a loop on nega-
321         tive numbers.  Entering an equation with no left hand side  means  that
322         the LHS is the same as in the line previously entered.
323  
324         We  have  seen  that a formal parameter can be a name or a literal con-
325         stant.  It can also be a pattern to match list  structure  as  in  this
326         example - `rotor' carries out a simple rotation on lists of length 3.
327  	      rotor [a,b,c] = [b,c,a]
328  
329         To  match  lists  of unknown length we use a pattern involving `:', for
330         example the functions `hd', `tl', which return the first element  of  a
331         list,  and  the	remainder  of  the list without the first element, are
332         defined
333  	      hd (a:x) = a
334  	      tl (a:x) = x
335  
336         Another example is this function which copies lists of length  <=2  and
337         extracts the first 2 elements of lists with length >2.
338  	      take2 [] = []
339  	      take2 [a] = [a]
340  	      take2 (a:b:x) = [a,b]
341         Note that ':' is right associative so `a:b:x' means `a:(b:x)'.
342  
343         In  summary, an LHS consists of the name being defined followed by zero
344         or more formal parameters.  Each formal parameter can be
345  	      a name like x or height
346  	      a literal number or string like 3 or "bill"
347  	      a pattern like [p,q,r] or (a : x)
348  	      where any of the p, q, r, a, x could themselves be a name,  lit-
349  	      eral or pattern.
350         Names  introduced  by  formal  parameters  are local to the equation in
351         which they appear.
352  
353         An equation with one or more patterns  in  its  LHS  applies  when  the
354         actual parameters of a function invocation match the corresponding for-
355         mal parameters; that is they have the same list	structure  and,  where
356         the pattern contains a literal, the values are equal.  If there is also
357         a guard, that must evaluate to "TRUE".
358  
359         Where a definition has more than one equation they must	all  have  the
360         same number of formal parameters.  Notwithstanding this, it is possible
361         in KRC to define functions which take a variable number	of  arguments,
362         because the right hand sides can be of varying type. (Terminology - the
363         actual parameters of a function are also called its arguments.)
364  
365         KRC supports the interactive development of scripts.
366  
367         To enter definitions in the script during a session you simply type  in
368         the  equations and comments at the prompt, one at a time.  You can then
369         enter expressions to test your definitions and edit them (i.e.  delete,
370         reorder	etc)  using the COMMANDS listed earlier and re-enter equations
371         as needed.  The line editing facilities provided by "linenoise"	and/or
372         the use of a mouse to cut and paste make this task relatively easy.
373  
374         If you enter an equation with the same LHS and guard as an existing one
375         it will replace it.  Entering a comment will replace an earlier comment
376         on the same name.  To delete a comment enter an empty replacement
377  	      name :-;
378  
379         Another	way of proceeding is to use an editor to create the script and
380         then start a krc session with it as  the  file.	 The  KRC  system  was
381         designed to allow it to be used without a separate editor (back in 1980
382         screen editors like vi and emacs were not widely available as they  are
383         now).
384  
385  IDENTIFIERS
386         The  names  used  in scripts and expressions are built from A-Z a-z 0-9
387         underscore (_) and apostrophe ('), start with a letter and  can	be  of
388         any length.  Case is significant, so X and x are different identifiers.
389         Note that KRC has no reserved words.
390  
391  DATA TYPES
392         KRC has four data types: numbers, strings, lists and functions.
393  
394         The four types of value have the same "civil rights" - any value can be
395         (i)  named,  (ii) included in a list, (iii) passed to a function as its
396         argument, (iv) returned by a function as result.
397  
398         There is no static type system -  values  of  different	types  can  be
399         freely  mixed,  for  example  as  elements of a list and a function can
400         accept arguments of more than one type and return results of  different
401         types  for  different inputs.  Type errors, e.g. trying to multiply two
402         strings, are detected at run time.  Languages of  this  kind  (LISP  is
403         another	example) are often called `typeless', but dynamically typed is
404         more accurate.
405  
406         A value can be tested by the four functions `number', `string',	`list'
407         and  `function'	and  returns  "TRUE" for one of these, "FALSE" for the
408         others. There is also a function `char'	which  recognises  strings  of
409         length  1  and a function `bool' which reconises the strings "TRUE" and
410         "FALSE".
411  
412         Numbers are integers (whole numbers, positive, negative and zero) writ-
413         ten in the usual decimal notation, e.g. 3 -17 500
414  
415         Strings are sequences of characters enclosed in double quotes, e.g.
416  	      "cattle" "oh my!"
417  
418         Control	characters  are  written using `\', e.g. "\n" is newline.  The
419         escape conventions are as in C
420  	      \a (bell) \b (backspace) \f (formfeed) \n (newline) \r (carriage
421  	      return) \t (tab) \v (vertical tab) \\ (backslash) \' \"
422         and numeric character codes
423  	      \ddd (up to three decimal digits).
424         KRC  character  codes are in the range 0-255 (of which 0-127 are ascii,
425         the meaning of codes above 127 depends on the locale).
426  
427         Note the strings "TRUE", "FALSE" are used as truthvalues, there	is  no
428         separate Boolean type.
429  
430         KRC has no separate type `character' distinct from `string'.  A charac-
431         ter is just a string of length 1, e.g. "a" (you cannot  write  this  as
432         'a', that would not be recognised).
433  
434         The prelude function `explode' converts a string into a list of charac-
435         ters, e.g.
436  	      krc> explode "hello"?
437  	      ["h","e","l","l","o"]
438  
439         KRC treats strings as atomic; they are stored uniquely in packed  form.
440         Strings	can be tested for equality or order without unpacking them but
441         to access the internal structure you must use `explode'.
442  
443         There is a function `implode' which compresses a list of strings into a
444         single  string,	but  this is less often needed.  Processing of textual
445         data is typically done on lists of characters (or sometimes trees)  and
446         given  `!'  there  is  no need to convert the result back into a single
447         string before printing.
448  
449         Lists are written using square brackets and  commas  between  elements,
450         e.g. [1,2,3,"eric"].  Note the empty list, [] and singletons, e.g. [3].
451  
452         An important operation on lists is `:' which prefixes an element to the
453         front of a list.  So `a:[]' is `[a]', `a:b:[]' is `[a,b]'  and  so  on.
454         Note  also  the	`++'  operator which appends one list to another.  The
455         elements  of `x++y' are those of `x' followed by those of `y'.
456  
457         As some, or all, of the elements of a  list can be lists it is possible
458         to  construct  multi-dimensional arrays (as lists of lists of ...)  and
459         more generally trees, of any shape.  Lists can be of  infinite  length,
460         for example
461  	      ones = 1 : ones
462         is an infinite list of ones and
463  	      abyss = ["down",abyss,"up"]
464         is  a  tree  of infinite depth.	These examples are possible because of
465         KRC's general strategy of lazy evaluation, which includes not  evaluat-
466         ing the parts of a structure until they are accessed.
467  
468         There  is  a  notation `[a..b]' for a sequence of consecutive integers,
469         e.g. `[-10..10]' is a list with 21 elements.  This notation also has an
470         infinite form, e.g. `[2..]'  is a list of the integers starting at 2.
471  
472         Similarly  the  notation  `[a,b..c]'  can  be  used  for  an arithmetic
473         sequence running from a to c with step (b-a).  E.g. [1,3..99]  are  the
474         odd  numbers  from  1  to  99.	Again  this has an infinite form, e.g.
475         [0,-5..]
476  
477         A list can be applied to a non-negative number, n say, to  extract  its
478         n'th element (counting from 0). So given
479  	      x = ["mon","tue","wed","thu","fri"]
480         then `x 0' is "mon", `x 6' is "fri", and `x 7' is an error.  A list can
481         therefore be supplied in a context where a function  is	expected,  for
482         example as an operand of `.' the functional composition operator.
483  
484         Functions:  a  function	calculates  an	output	value from given input
485         value(s).  The rules of calculation are given by its defining equations
486         (except for a few built-in functions defined in machine code).
487  
488         Applying  a function to its input values (or arguments) is done by jux-
489         taposition, e.g.
490  	      f x y
491         If an argument is an operator expression or another  function  applica-
492         tion it needs parentheses to force the correct parse. E.g.
493  	      f (g x) (y+2)
494  
495         A  prefix  or infix operator in single quotes denotes the corresponding
496         one- or two-argument function, e.g.
497  	      ops = ['+', '-', '*', '/']
498         is a list of the four functions of arithmetic.  See below, under OPERA-
499         TORS.
500  
501         Continued  application:	a  function application can return a function,
502         e.g. (ops n) is a function, which one depends on `n'.  We  can  immedi-
503         ately apply this to its arguments, thus
504  	      ops n x y
505         We  could  write  `(ops	n)  x y' but the parentheses are not needed as
506         function application is left associative.
507  
508         Partial application: a function of two or more arguments can be applied
509         to  a  smaller number of arguments and the result is a function that is
510         waiting for the remaining arguments.  For example
511  	      double = '*' 2
512         is a function that can be applied to a number and will multiply	it  by
513         2.
514  
515         Partial application works because KRC uses a model of functions derived
516         from combinatory logic.	In this model, all functions actually  take  a
517         single  argument.  An n-ary function, for n>1, is a function that, when
518         applied to its argument, returns an (n-1)ary function that  is  waiting
519         for the next argument. So taking the case n=3 as an example
520  	      f a b c
521         means
522  	      ((f a) b) c
523         but  because  of the left-associative rule the parentheses are normally
524         omitted.
525  
526  OPERATORS
527         The following table lists KRC's prefix and infix operators in order  of
528         increasing binding power.
529  
530         The  second  column  gives associativity:- a left associative operator,
531         e.g. `-' has
532  	      a - b - c  ==>  (a - b) - c
533         while a right associative operator, e.g. `++' has
534  	      a ++ b ++ c  ==>	a ++ (b ++ c)
535         Infix operators in the same row have the same  binding  power  and  are
536         jointly right or left associative.
537  
538         The  third column gives a brief statement of meaning.  Where needed the
539         notes below add further detail.
540  
541         operator 	 associativity	 meaning
542  
543         :  ++  --	 right		 list prefix, append, listdiff
544         |		 right		 logical or
545         &		 right		 logical and
546         \		 prefix 	 logical not
547         > >= \= == <= <	 see below	 comparisons
548         + -		 left		 add, subtract
549         + -		 prefix 	 plus, minus
550         * / %		 left		 multiply, integer divide, remainder
551         ** .		 right		 exponent, function-compose
552         #		 prefix 	 length of list
553  
554         The application of a function to its arguments binds more tightly  than
555         any  operator.  Parentheses (...) can be inserted freely in expressions
556         to enforce the intended parse or to make it clearer  to	the  reader  -
557         redundant  parentheses  do not change the meaning (this is true both in
558         expressions and in formal parameters).
559  
560         The operators : (prefix) and ++ (append) have been  discussed  earlier,
561         in  the section on DATA TYPES.  The expression x -- y returns a list of
562         the elements of x without those that appear in y, the exact  definition
563         is given by the prelude function listdiff.
564  
565         The logical operators |, & do not evaluate their second operand if this
566         is not needed.
567  	      a | b
568         returns "TRUE" if a is "TRUE", otherwise it returns b.  Similarly
569  	      a & b
570         returns "FALSE" if a is "FALSE", otherwise it returns b.
571  
572         The relational operators >, >=, ==, <=, < have a special  syntax  which
573         allows continued relations, as commonly used in mathematics books.  For
574         example
575  	      0 <= x <= 10  means  0 <= x & x <= 10
576  	      a == b == c < 0  means  a == b & b == c & c < 0
577  
578         The operators == and \= can be used to test for equality or  inequality
579         on any pair of values, returning "TRUE" or "FALSE". Values of different
580         types are always unequal.  Two lists count as equal if and only if they
581         are  of	the  same  length and (recursively for sublists) corresponding
582         elements are equal.
583  
584         Equality tests between functions give unpredictable results and	should
585         not   be   used.    (Example:   `map == map'   has   value  "TRUE"  but
586         `map abs == map abs' is "FALSE".)
587  
588         The order testing operators > >= <= < work on numbers in the usual  way
589         and on strings compare according to the C function strcmp().  For words
590         all in upper case, or all in lower case,  this  amounts	to  dictionary
591         order, but be aware that upper case letters precede lower case letters,
592         so "ZEBRA" < "ant". It is an error  to  test  lists  or	functions  for
593         order, or two values of different type.
594  
595  	+  -  *  /  are the usual arithmetic operations, with % for remainder.
596         KRC arithmetic deals only with integers thus  `/'  discards  the  frac-
597         tional  part,  rounding	towards  0, while a % b takes the remainder on
598         dividing `a' by `b', the sign of the result being that  of  `a'	(these
599         rules for integer division and remainder are the same as C).
600  
601         Prefix  `-'  reverses  the  sign  of  its  integer  operand  (leaving 0
602         unchanged).  A negative constant like `-1' is, syntactically, an opera-
603         tor  expression	and  must  be parenthesised when passed to a function,
604         thus `f(-1)' whereas `f -1' would attempt to subtract 1 from f.	Prefix
605         `+' does nothing and is discarded.
606  
607         a ** b raises `a' to the power of `b' which must be non-negative.
608  
609         The composition of two functions `f . g' is defined as follows
610  	      (f . g) x  =  f (g x)
611  
612         The operator # gives the length of a list, for example `#[1,2,3]' is 3.
613         To find the length of a string use the prelude function printwidth.
614  
615         A prefix or infix operator in single quotes denotes  the  corresponding
616         one-  or  two-argument function.  For example '+' is the addition func-
617         tion and '#' and '\' are functions which take the length of a list  and
618         the  negation of a truthvalue.  Note that '-' is subtraction, for unary
619         minus you can use the prelude function neg.
620  
621  ZF EXPRESSIONS
622         ZF expressions are a notation  to  generate  lists  from  other	lists.
623         (These  would  now  called  list  comprehensions, a term coined by Phil
624         Wadler in 1985.)
625  
626         We start with some simple examples
627  	      {n*n; n<-[1..]}
628         is a list of  all  square  numbers  [1,4,9,16,25...].   The  expression
629         before  `;' is the body of the ZF expression while `n<-[1..]' is called
630         a generator and `n' is a local variable	of  the  ZF  expression.   The
631         effect  is  to  create  a list of the values taken by the body for each
632         value of `n' drawn from the list given in its generator.
633  
634         The next example is a function for finding the factors of a number
635  	      factors n = {r; r<-[1..n/2]; n%r==0}
636         This makes a list of the numbers between  1  and  n/2  which  divide  n
637         exactly.   The expression after the second semicolon is called a filter
638         - only those values of the generator are used for which the  filter  is
639         "TRUE".
640  
641         A ZF expression can have two or more generators, so
642  	      {a+b; a<-[1,2,3]; b<-[10,20,30]}
643         gives you a list of nine two-digit numbers.
644  
645         Our  last  example  finds  all  positions  on a chess board which are a
646         knight's move from [x,y]
647  	      knights_move [x,y] = {[i,j]; i,j<-[1..8]; (i-x)**2 + (j-y)**2 ==
648  	      5}
649         Searching  the whole board in this way is not very efficient, but never
650         mind.  Note that `i,j<-[1..8]' is shorthand for two generators with  i,
651         j both drawn from [1..8].
652  
653         The general form of a ZF expression is
654  	      {expression; qualifier; ... ; qualifier}
655  	      with  one  or more qualifiers, each of which is either a genera-
656  	      tor, of the form
657  		      name-list <- expression
658  	      or a filter, which is an expression whose  value	is  "TRUE"  or
659  	      "FALSE".
660  
661         If  the	first qualifier is a generator, which is usually the case, the
662         initial `;' can be written `|', which aids readability.
663  
664         For examples of programming with  ZF  expressions  see  David  Turner's
665         papers  "The  Semantic  Elegance  of Applicative Languages'' (1981) and
666         "Recursion Equations as a Programming Language" (1982).
667  
668         (Historical note: The semantics of ZF expressions in  KRC  differ  from
669         those of modern list comprehensions in interleaving outputs of multiple
670         generators to ensure that all combinations are eventually reached, even
671         with  two or more infinite generators.  The motivation was to make them
672         behave more like set comprehensions, whence the use of {}.   List  com-
673         prehensions  with  square  brackets  and the now familiar "nested loop"
674         semantics first appeared in Miranda, in 1984.)
675  
676  THE PRELUDE
677         When KRC is started it first loads the prelude, a library  of  standard
678         definitions,  most  of  which  are in KRC but some are in machine code,
679         including functions to access the operating system (e.g. read, write).
680  
681         To list the names defined in the currently loaded prelude during a  KRC
682         session, type
683  	      /lib
684         You can inspect any of the definitions by typing the name, e.g.
685  	      map
686         Each  has an comment explaining what it does, in addition to its defin-
687         ing equations.
688  
689         The standard prelude is usually	at  /usr/lib/krc/prelude  but  may  be
690         placed  elsewhere  by  the installer. To view the standard prelude in a
691         KRC session, say "/help prelude".
692  
693         Another library in place of the standard prelude can  be  specified  on
694         the  command  line  when  KRC  is invoked by the option -l lib.	If you
695         invoke KRC with option -n, no prelude is loaded.
696  
697         If KRC is invoked with option -L, a legacy prelude is used in place  of
698         the standard one. To view this in a KRC session, say "/help lib1981".
699  
700         Note that without a prelude you cannot use ZF expressions, whose imple-
701         mentation requires interleave nor can you use the `--' operator,  which
702         requires the function listdiff.
703  
704  LINE EDITING AND ESCAPE TO UNIX SHELL
705         Line editing: if KRC is compiled with the "linenoise" module, the arrow
706         keys and other keys can be used to scroll back and forth through  lines
707         typed  in  a  KRC session, to edit and resubmit them.  For a summary of
708         available key bindings, with and without "linenoise", say /help keys in
709         a KRC session.
710  
711         Escape  to  Unix  shell:  type Ctrl-Z to suspend KRC and return to Unix
712         command line, say fg to resume the KRC session.
713  
714  MAKING UNIX COMMANDS
715         You can write a Unix command in KRC by  making  its  script  executable
716         through	the  "magic  string"  mechanism. To do this, add a line as the
717         start of the script, of the form:
718  	      #! /usr/bin/krc -e expression!
719         where expression is to be evaluated when the program is run.  This  can
720         be  a  KRC expression of any complexity, terminated by `?' if its value
721         is to be shown with its structure or `!' if it is to be flat-printed.
722  
723         Other flags such as "-l lib" for an alternative prelude, "-h size"  for
724         a larger heap, can precede "-e".
725  
726         The  name  by  which the script is called, followed by the command-line
727         arguments that the user supplies when it is run, are placed in  a  list
728         of strings called "argv".
729  
730         Example:  A  simple  command to display the contents of files.  Put the
731         following 2 lines in a file called "list".
732  	       #! /usr/bin/krc -e main!
733  	       main = map read (tl argv)
734         then make it executable
735  	       chmod +x list
736         now you can use it, for example
737  	       ./list list
738         will display the contents of the file itself.
739  
740         Any KRC script can be made executable by placing a  "magic  string"  at
741         the  start.   When  used as the script in an interactive KRC session an
742         initial line in `#!'  is treated as  a  comment	and  ignored;  it  has
743         effect  only  if  the  file is invoked as a command on the Unix command
744         line.
745  
746  LANGUAGE CHANGES
747         The KRC language described here is as David Turner designed  it	around
748         1980, except for the following changes.
749  
750         The  base  for indexing lists has been changed from 1 to 0.  The option
751         -z reverts to lists being indexed from 1 (this may be needed for legacy
752         KRC scripts dating from the 1980's).
753  
754         A  revised  prelude has been provided, with some more efficient defini-
755         tions (e.g. reverse, sort) and a more modern collection	of  functions.
756         A legacy prelude from 1981 is also available (option -L).
757  
758         Escape characters in strings, "\n" etc., as in C, have been added.  KRC
759         as originally designed used instead names for special characters: nl np
760         quote  tab  vt,	these  remain  in  the	prelude.   Example: instead of
761         "123\tgo\n" you can say ["123",tab,"go",nl] to get the same effect with
762         ``!''.
763  
764         A  distinction has been introduced between `=', definitional equals and
765         `==' the equality test (KRC originally used `=' for both).
766  
767         In-line comments, from "||" to end of line, have been added, thus
768  		      || this is a comment
769         these don't fit	very  naturally  with  KRC's  model   of   interactive
770         script  development   as  they  are  discarded  when  entered  during a
771         session.  But the facility is useful for  scripts  prepared   with   an
772         editor	as it allows comments on individual equations and on the whole
773         script.
774  
775  LEGACY SYNTAX
776         With option -z these alternative operator forms are accepted  and  con-
777         verted to their standard variants:
778  	      ~  as a synonym for \ (prefix not)
779  	      ~= as a synonym for \= (not-equals)
780  	      = as a synonym for == (equality test)
781  
782  LIMITATIONS
783         Guards do not work correctly with simple definitions, for example
784  	      feb = 29, leap_year
785  		  = 28
786         fails with strange error when leap_year="FALSE".  The language as orig-
787         inally defined did not allow guards with simple definitions, only  with
788         functions.   The  syntactic restriction has been removed but the corre-
789         sponding semantics still needs fixing.
790  
791         The length of a string limited to 255 characters.  The  space  used  by
792         strings	created during a session is never freed, mitigated only by the
793         fact that multiple copies of the same string  are  shared.  This  means
794         that  programs which create a lot of temporary strings as part of their
795         operation will soon run out of the space in which strings, identifiers,
796         file  names  and  comments are stored.  Note, however, that KRC's ``!''
797         output mode removes much of the need to create temporary strings.
798  
799         Numbers are limited in range to	that  of  the  underlying  processor's
800         machine word, i.e. they are signed 32-bit or 64-bit integers.  Calcula-
801         tions which exceed this range cause a run-time error.
802  
803         If linenoise is enabled, multiline comments cannot be entered  interac-
804         tively in a KRC session.
805  
806  FILES
807         /usr/lib/krc/prelude
808  	      The standard prelude.
809  
810         /usr/lib/krc/lib1981
811  	      A legacy prelude dating from 1981 (invoked by option -L).
812  
813         KRC  looks  for	the  prelude  first  in  ./krclib  if present, then in
814         /usr/lib/krc (this may be changed by the installer).
815  
816  SEE ALSO
817         http://krc-lang.org/
818  	      The KRC home page.
819  
820         Recursion Equations as a Programming Language, D.  A.  Turner,  January
821         1982
822  	      This  includes  an overview of the KRC language and can be found
823  	      at the above website.
824  
825         http://github.com/antirez/linenoise
826  	      The "linenoise" line-editing module (the version	included  with
827  	      the  KRC	sources has been lightly edited to configure it appro-
828  	      priately).
829  
830  AUTHOR
831         The KRC system was designed by David Turner who implemented it in  BCPL
832         for the EMAS operating system from November 1979 to October 1981.
833  
834         This  implementation  was  created  by  translating  the  original BCPL
835         sources into C for the Unix family of operating systems.
836  
837         KRC is Copyright (c) D. A. Turner 1981 and is released  under  an  open
838         source  license,  for terms see the file "COPYING" included in the dis-
839         tribution.
840  
841  
842  
843  				  2016-03-31				KRC(1)