home *** CD-ROM | disk | FTP | other *** search
/ ftp.uni-stuttgart.de/pub/systems/acorn/ / Acorn.tar / Acorn / acornet / dev / gofer.spk / docsrc / doc220 next >
Text File  |  1994-06-06  |  236KB  |  5,691 lines

  1. .co This is the `source form' of the user documentation for Gofer, to be
  2. .co processed using my simple prn formatter before being printed.
  3. .co
  4. .co Mark P. Jones  August 1991
  5. .co-------------------------------------------------------------------|
  6. .>ch00
  7. .op
  8. .ti Introduction to Gofer
  9.  
  10.  
  11.  
  12.  
  13.  
  14.  
  15.          __________   __________   __________   __________   ________
  16.         /  _______/  /  ____   /  /  _______/  /  _______/  /  ____  \
  17.        /  / _____   /  /   /  /  /  /______   /  /______   /  /___/  /
  18.       /  / /_   /  /  /   /  /  /  _______/  /  _______/  /  __   __/
  19.      /  /___/  /  /  /___/  /  /  /         /  /______   /  /  \  \ 
  20.     /_________/  /_________/  /__/         /_________/  /__/    \__\
  21.  
  22.     Functional programming environment, Version 2.20
  23.  
  24.     Copyright Mark P Jones 1991.
  25.  
  26.  
  27.  
  28.  
  29.  
  30.  
  31.             A N   I N T R O D U C T I O N   T O   G O F E R
  32.  
  33.  
  34.      draft version only --- please report any errors, suggestions for
  35.     improvements, extensions (or deletions!) to jones-mark@cs.yale.edu
  36.  
  37.  
  38.            This version includes a number of small corrections
  39.                    made since the original release.
  40.  
  41.    --------------------------------------------------------------------
  42.    Permission to use, copy, modify, and distribute this software and its
  43.    documentation for any personal or educational use without fee is hereby
  44.    granted, provided that:
  45.     a) This copyright notice is retained in both source code and
  46.        supporting documentation.
  47.     b) Modified versions of this software are redistributed only if
  48.        accompanied by a complete history (date, author, description) of
  49.        modifications made; the intention here is to give appropriate
  50.        credit to those involved, whilst simultaneously ensuring that any
  51.        recipient can determine the origin of the software.
  52.     c) The same conditions are also applied to any software system
  53.        derived either in full or in part from Gofer.
  54.  
  55.    The name "Gofer" is not a trademark, registered  or  otherwise,  and
  56.    you are free to mention this name in published material, public  and
  57.    private correspondence, or other documents  without  restriction  or
  58.    obligation.
  59.  
  60.    Gofer is provided "as is" without express or implied warranty.
  61.    --------------------------------------------------------------------
  62. .pa
  63. .po
  64. .pn -100
  65.                       T A B L E   O F   C O N T E N T S 
  66.  
  67.  
  68. .in contents
  69. .pa
  70. .pn 1
  71. .co-------------------------------------------------------------------|
  72. .>ch01
  73. .ST 1. INTRODUCTION
  74.  
  75. Gofer is a functional  programming  environment  (in  other  words,  an
  76. interpreter) that I have implemented for my own personal use as part of
  77. my research  into  `qualified  types'.   Nevertheless,  the  system  is
  78. sufficiently complete for me to believe that Gofer may be  of  interest
  79. and use to others interested in the field of functional programming.
  80.  
  81. These notes give a brief introduction to the Gofer system  and  include
  82. some examples of Gofer  programs.   They  are  not  the  notes  that  I
  83. originally intended to write, being somewhat longer  and  perhaps  more
  84. tutorial in nature.  Nevertheless,  you  will  not  be  able  to  learn
  85. functional programming from this document alone.  A  number  of  useful
  86. references are given in the reading list at the end of  this  document.
  87. In particular, the book by Bird and Wadler [1] is particularly good  as
  88. a general introduction to the use, techniques and theory of  functional
  89. programming.  Although their notation is  a  little  different from the
  90. language used by Gofer, it is  a  relatively  straightforward  task  to
  91. translate between the two, and some suggestions for this are given in a
  92. appendix D.  More importantly, the underlying  semantics  of  Gofer  do
  93. correspond to those expected by the authors of [1].
  94.  
  95. Whereas the work involved in investigating and implementing  the  ideas
  96. on which Gofer is based were motivated largely by  my  own  program  of
  97. work, the writing of these notes has rather more to do  with  the  hope
  98. that Gofer will be  useful  to  others.   I  would  therefore  be  very
  99. grateful for any feedback on any aspect of the these notes (or  of  the
  100. Gofer system itself).  Please let me know if you discover  any  errors,
  101. or if you find particular  sections  of  these  notes  rather  hard  to
  102. follow.  Suggestions for  improvements  or  extensions  are  more  than
  103. welcome.
  104. .pa
  105. .co-------------------------------------------------------------------|
  106. .>ch02
  107. .ST 2. BACKGROUND AND ACKNOWLEDGEMENTS
  108.  
  109. The language supported by Gofer is both syntactically and  semantically
  110. similar to that of the functional programming language Haskell [5].  My
  111. principal task in the implementation of Gofer  has  therefore  been  to
  112. decide which  features  I  should  omit  and  then  to  implement  what
  113. remains.  Features common to both include:
  114.  
  115.   o  Non-strict semantics (lazy evaluation).
  116.   o  Higher-order functions.
  117.   o  Extended polymorphic type system  with  support  for  user-defined
  118.      overloading.
  119.   o  User-defined algebraic datatypes.
  120.   o  Pattern matching.
  121.   o  List comprehensions.
  122.   o  Facilities for  I/O,  whilst  retaining  referential  transparency
  123.      within a program.
  124.  
  125. For the  benefit  of  readers  familiar  with  Haskell,  the  following
  126. features of Haskell are not supported in the standard version of Gofer:
  127.  
  128.   o  Modules.
  129.   o  Arrays.
  130.   o  Defaults for unresolved overloading.
  131.   o  Derived instances of standard classes.
  132.   o  Contexts in datatype definitions.
  133.   o  Full range of numeric types and classes.
  134.  
  135. But Gofer is not just a partial  implementation  of  Haskell;  it  also
  136. includes a number of experimental features which extend the type system
  137. in several ways:
  138.  
  139.   o  An alternative approach to type classes which avoids the need  for
  140.      construction  of  dictionaries  during  the   evaluation   of   an
  141.      expression.
  142.   o  Type classes may take multiple parameters.
  143.   o  Instances  of  type  classes   may   be   defined   at   arbitrary
  144.      non-overlapping types.
  145.   o  Contexts may include arbitrary type expressions.
  146.  
  147. These extensions stem from my own research [8, 9, 10, 11, 12] and  were
  148. among the principal motivations for the  development  of  Gofer.   Full
  149. details of the differences between Gofer and Haskell 1.1 are  given  in
  150. appendix C.
  151.  
  152. Gofer would not have been implemented without my original  introduction
  153. to functional programming using  Orwell  [6],  and  I  am  particularly
  154. grateful to Quentin Miller for answering so many of my questions  about
  155. functional programming and about the Orwell system  in  particular.   I
  156. should also like to mention the influence of the  Haskell  B.  compiler
  157. from Lennart Augustsson and Thomas Johnsson and based on their  earlier
  158. LML compiler [7].
  159.  
  160. Right from the beginning, I wanted to be able to use Gofer on  a  range
  161. of machines - and in particular, on the humble PC that I use  at  home.
  162. With this in mind, Gofer was actually developed on that same  PC  using
  163. Borland's Turbo C 1.5 and a public domain version of  the  yacc  parser
  164. generator that I picked up some time ago.  Gofer was also written  with
  165. some degree of portability in mind and has subsequently  been  compiled
  166. to run on Sun workstations.  I hope it will also be possible to port it
  167. to other platforms.  It is  my  intention  that  Gofer  be  distributed
  168. complete with source code and I hope that this will be of  interest  to
  169. some users.
  170.  
  171. Many of the ideas used in the back-end of the Gofer  system  (i.e.  the
  172. compiler and abstract machine) originate from  the  chapters  of  Simon
  173. Peyton Jones textbook [2]; I very much doubt whether Gofer  would  have
  174. been  completed  without  frequent  reference  to   that   book.    The
  175. lambda-lifter used in Gofer is based  on  Thomas  Johnsson's  algorithm
  176. described in [3].
  177.  
  178. On  the  theoretical  side,  I'm  grateful  to  Phil  Wadler  for   the
  179. encouragement that he has given me with my  work  on  qualified  types.
  180. Many of the basic ideas that I have used were inspired by his  original
  181. paper motivating the use of type classes [4].
  182. .pa
  183. .co-------------------------------------------------------------------|
  184. .>ch03
  185. .ST 3. STARTING GOFER
  186.  
  187. The Gofer interpreter is usually entered by giving the command `gofer',
  188. after which a display something like the  following  will  normally  be
  189. produced:
  190.  
  191.     Gofer Version 2.20
  192.  
  193.     Reading script file "/gofer/prelude":
  194.     Parsing........................................................
  195.     Dependency analysis............................................
  196.     Type checking..................................................
  197.     Compiling......................................................
  198.  
  199.     Gofer session for:
  200.     /gofer/prelude
  201.     Type :? for help
  202.     ?
  203.  
  204. The file name "/gofer/prelude" mentioned in the  output  above  is  the
  205. name of a file of standard definitions which are loaded into Gofer each
  206. time that the interpreter is started.  By default,  Gofer  reads  these
  207. definitions from  a  file  called  "prelude"  in  the  current  working
  208. directory.  Alternatively you can set the environment variable GOFER to
  209. the name of the  standard  prelude  file,  which  will  then  be  used,
  210. whatever the current working directory might be.
  211.  
  212. Most commands in Gofer take the form of a colon followed by one or more
  213. characters which distinguish one command from another.  There  are  two
  214. commands which are particularly worth remembering:
  215.  
  216.   o  :q  exits the  Gofer  interpreter.   On most systems, you can also
  217.      exit from Gofer by typing the end of  file  character  (^Z  on  an
  218.      MS-DOS machine, usually ^D on a unix based machine).
  219.  
  220.   o  :?  prints a list of all the commands,  which can be useful if you
  221.      forget the name of the command that you want to use.
  222.  
  223. The complete range of commands supported by the  Gofer  interpreter  is
  224. described in appendix F.
  225.  
  226. Note that the interrupt key (^C on most systems) can  be  used  at  any
  227. time whilst using Gofer to abandon the process of reading in a file  of
  228. function definitions or the evaluation  of  an  expression.   When  the
  229. interrupt key is detected, Gofer prints the string "{Interrupted!}" and
  230. prints the "? " prompt so that further commands can be entered.
  231.  
  232. .pa
  233. .co-------------------------------------------------------------------|
  234. .>ch04
  235. .ST 4. USING GOFER - A BASIC INTRODUCTION
  236.  
  237. Using Gofer is rather like using a high-level programmable  calculator;
  238. Once the interpreter is loaded, the system  prints  a  prompt  "?"  and
  239. waits for you to enter an expression, and then press the enter (return)
  240. key.  Once the input is complete, Gofer evaluates  the  expression  and
  241. prints its value on the terminal,  before  returning  to  the  original
  242. prompt and waiting for the next expression.  For example:
  243.  
  244.     ? (2+3)*8
  245.     40
  246.     (5 reductions, 9 cells)
  247.     ? sum [1..10]
  248.     55
  249.     (91 reductions, 130 cells)
  250.     ? 
  251.  
  252. In the first example, the user entered the expression "(2+3)*8",  which
  253. was evaluated by Gofer and the result "40" printed on the terminal.  At
  254. the end of any calculation, Gofer displays the number of reductions  (a
  255. measure of the amount of work) and cells (a measure of  the  amount  of
  256. memory) that were used during the calculation.  These  figures  can  be
  257. useful for comparing the performance of different ways of carrying  out
  258. the same calculation.
  259.  
  260. In the second example, the user typed  the  expression  "sum  [1..10]".
  261. The notation "[1..10]" represents the list of integers between 1 and 10
  262. inclusive, and "sum" is a  standard  function  which  can  be  used  to
  263. determine the sum of a list of integers.  Thus the result  obtained  by
  264. Gofer is:
  265.  
  266.           1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10  =  55
  267.  
  268. We could have typed this sum into Gofer directly:
  269.  
  270.     ? 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10
  271.     55
  272.     (10 reductions, 23 cells)
  273.     ? 
  274.  
  275. and this calculation is certainly more efficient as it uses only  1/9th
  276. of the number of reductions and 1/5th of the number  of  cells  as  the
  277. original calculation.  On the other hand, the  original  expression  is
  278. much shorter and you are much less likely to make a mistake  typing  in
  279. the expression "sum [1..200]" than you would be if you tried  to  enter
  280. the sum of the integers from 1 to 200 directly.
  281.  
  282. You will learn more about the kind of expressions that can  be  entered
  283. into Gofer in the rest of this document.
  284. .pa
  285. .co-------------------------------------------------------------------|
  286. .>ch05
  287. .ST 5. STANDARD AND USER-DEFINED FUNCTIONS
  288.  
  289. The function "sum" used in the examples above, and indeed the  addition
  290. and multiplication functions (+) and (*), are  all  standard  functions
  291. which are included as part of a large collection  of  functions  called
  292. the `standard prelude' which are loaded into the Gofer system each time
  293. that you start the interpreter.  Quite a number of useful  calculations
  294. can be carried out using these functions alone, but  for  more  general
  295. use you can also define your own functions and store the definitions in
  296. a file so that these functions can be loaded and used by by  the  Gofer
  297. system.  For example, suppose that you create a file "fact"  containing
  298. the following definition:
  299.  
  300.      fact n = product [1..n]
  301.  
  302. The "product" function is another standard function which can  be  used
  303. to calculate the product of a list of integers, and so the  line  above
  304. defines a  function  "fact"  which  calculates  the  factorial  of  its
  305. argument.  In standard  mathematical notation,  fact n = n!   which  is
  306. usually defined informally by an equation of the form:
  307.  
  308.                  n! = 1 * 2 * ... * (n-1) * n
  309.  
  310. Once you become familiar with the notation used by Gofer, you will  see
  311. that the Gofer definition of the  factorial  function  is  really  very
  312. similar to this informal mathematical definition.
  313.  
  314. In order to use this definition from the  Gofer  interpreter,  we  must
  315. first load the definitions of  the  file  into  the  interpreter.   The
  316. simplest way to do this uses the ":l" command:
  317.  
  318.     ? :l fact
  319.     Reading script file "fact":
  320.     Parsing......................................................
  321.     Dependency analysis..........................................
  322.     Type checking................................................
  323.     Compiling....................................................
  324.  
  325.     Gofer session for:
  326.     /gofer/prelude
  327.     fact
  328.     ?
  329.  
  330. Notice the list of filenames displayed after "Gofer session for:"; this
  331. tells you which files of definitions are currently being used by Gofer,
  332. the first of which is the  file  containing  the  definitions  for  the
  333. standard prelude.  Since the file  containing  the  definition  of  the
  334. factorial function has now  been  loaded,  we  can  make  use  of  this
  335. function in expressions entered to the interpreter:
  336.  
  337.     ? fact 6
  338.     720
  339.     (57 reductions, 85 cells)
  340.  
  341. For another example, recall the  standard  mathematical  formula  which
  342. tells us that  the  number  of  ways  of  choosing  r  objects  from  a
  343. collection of n objects is given by n! / (r! * (n-r)!).  In Gofer, this
  344. function can be defined by:
  345.  
  346.     comb n r = fact n /(fact r * fact (n-r))
  347.  
  348. In order to use this function, we can either edit the file "fact" which
  349. contains  the  definition  of  the  factorial  function,   adding   the
  350. definition of "comb" on a new line, or we can include the definition as
  351. part of an expression entered whilst using Gofer:
  352.  
  353.     ? comb 5 2 where comb n r = fact n /(fact r * fact (n-r))
  354.     10
  355.     (110 reductions, 161 cells)
  356.     ? 
  357.  
  358. The ability to define a function as part of an expression like this  is
  359. often quite useful.  However, if the function "comb" were likely to  be
  360. wanted on a number of occasions, it would be more sensible to  add  its
  361. definition to the contents of the file "fact",  instead  of  having  to
  362. repeat the definition each time it is used.
  363.  
  364. You will learn more about the functions defined in the standard prelude
  365. and find out  how  to  define  your  own  functions  in  the  following
  366. sections.
  367. .pa
  368. .co-------------------------------------------------------------------|
  369. .>ch06
  370. .ST 6. FUNCTION NAMES - IDENTIFIERS AND OPERATORS
  371.  
  372. As the examples of the previous section show, there are  two  kinds  of
  373. name that can be used for a function; identifiers  such  as  "sum"  and
  374. operator symbols such as "+" and "*".  Choosing the appropriate kind of
  375. name for a particular function  can  often  help  to  make  expressions
  376. involving that function easier to read.  If for  example  the  addition
  377. function was represented by the name "plus" rather  than  the  operator
  378. symbol "+" then the sum of the integers from 1 to 5 would  have  to  be
  379. written as:
  380.  
  381.                  plus (plus (plus (plus 1 2) 3) 4) 5
  382.  
  383. In this particular case, another way of writing the same sum is:
  384.  
  385.                  plus 1 (plus 2 (plus 3 (plus 4 5)))
  386.  
  387. Not only does the use of the identifier "plus" make  these  expressions
  388. larger and more difficult to read than the equivalent expressions using
  389. "+"; it  also  makes  it  very  much  harder  to  see  that  these  two
  390. expressions do actually have the same value.
  391.  
  392. Gofer distinguishes between the two types of name according to the  way
  393. that they are written:
  394.  
  395.   o  An  identifier  begins with a  letter  of the  alphabet optionally
  396.      followed by a sequence of characters, each of which  is  either  a
  397.      letter,  a  digit,  an  apostrophe  (')  or   an   underbar   (_).
  398.      Identifiers representing functions or variables must begin with  a
  399.      lower case letter (identifiers beginning with an upper case letter
  400.      are  used  to  denote  a  special  kind  of  function   called   a
  401.      `constructor function' described in section 11.1).  The  following
  402.      identifiers are examples of Gofer variable and function names:
  403.  
  404.        sum    f    f''    integerSum    african_queen    do'until'zero
  405.  
  406.      The following identifiers are reserved words in Gofer  and  cannot
  407.      be used as the name of a function or variable:
  408.  
  409.          case      of         where      let        in         if
  410.          then      else       data       type       infix      infixl
  411.          infixr    primitive  class      instance
  412.  
  413.   o  An  operator symbol  is written using one or more of the following
  414.      symbol characters:
  415.  
  416.          :  !  #  $  %  &  *  +  .  /  <  =  >  ?  @  \  ^  |  -
  417.  
  418.      In addition, the tilde character (~) is also  permitted,  although
  419.      only in the first position of an  operator  name.   [N.B.  Haskell
  420.      also makes the  same  restriction  for  the  minus/dash  character
  421.      (-)].   Operator  names  beginning  with  a  colon  are  used  for
  422.      constructor functions in the same  way  as  identifiers  beginning
  423.      with a capital  letter  as  mentioned  above.   In  addition,  the
  424.      following operator symbols have special uses in Gofer:
  425.  
  426.          ::    =    ..    @    \    |    <-    ->    ~    =>
  427.  
  428.      All other operator  symbols can be used as variables  or  function
  429.      names, including each of the following examples:
  430.  
  431.          +    ++    &&    ||     <=    ==    /=    //  .
  432.          ==>  $     @@     -*-   \/    /\    ...   ?
  433.  
  434.      [Note that each of the symbols in the first line is  used  in  the
  435.      standard prelude.  If you are interested in using Gofer to develop
  436.      programs for use with a Haskell compiler, you might also  want  to
  437.      avoid using the operator symbols := ! :+ and :% which are used  to
  438.      support features in Haskell not currently provided  by  the  Gofer
  439.      standard prelude.]
  440.  
  441. Gofer provides two simple mechanisms which make it possible to  use  an
  442. identifier  as  an  operator  symbol,  or  an  operator  symbol  as  an
  443. identifier:
  444.  
  445.   o  Any  identifier  will be treated as an  operator  symbol  if it is
  446.      enclosed in backquotes (`) -- for example, the  expressions  using
  447.      the "plus" function above are a little easier to read  using  this
  448.      technique:
  449.  
  450.                (((1 `plus` 2) `plus` 3) `plus` 4) `plus` 5
  451.  
  452.      In general, an expression of the form "x `op` y" is equivalent  to
  453.      the corresponding expression "op x y", whilst an  expression  such
  454.      as "f x y z" can also be written as "(x `f` y) z".
  455.  
  456.      [NOTE: For those using Gofer on a  PC,  you  may  find  that  your
  457.      keyboard does not have a backquote key!  In this case  you  should
  458.      still be able to enter a backquote by holding down the key  marked
  459.      ALT, pressing the keys '9' and then '6' on the numeric keypad  and
  460.      then releasing the ALT key.]
  461.  
  462.   o  Any  operator symbol  can be treated as an identifier by enclosing
  463.      it in parentheses.  For example, the addition function denoted  by
  464.      the operator symbol "+" is often written as "(+)".  Any expression
  465.      of the form "x + y" can also be written in the form "(+) x y".
  466.  
  467. There are two more technical problems which have to be dealt with  when
  468. working with operator symbols:
  469.  
  470.   o  Precedence: Given operator symbols (+) and (*), should "2 * 3 + 4"
  471.      be treated as either "(2 * 3) + 4" or "2 * (3 + 4)"?
  472.  
  473.      This problem is solved by assigning  each  operator  a  precedence
  474.      value (an integer in the range 0 to 9).  In a  situation  such  as
  475.      the  above,  we  simply  compare  the  precedence  values  of  the
  476.      operators involved,  and  carry  out  the  calculation  associated
  477.      with  the  highest  precedence  operator  first.    The   standard
  478.      precedence values for (+) and (*) are 6 and 7 respectively so that
  479.      the expression above will actually be treated as "(2 * 3) + 4".
  480.  
  481.   o  Grouping: The above rule  is only useful when the operator symbols
  482.      involved have  distinct  precedences.   For  example,  should  the
  483.      expression "1 - 2 - 3" be treated as either "(1 - 2) - 3" giving a
  484.      result of -4, or as "1 - (2 - 3)" giving a result of 2?
  485.  
  486.      This problem is  solved  by  giving  each  operator  a  `grouping'
  487.      (sometimes called its associativity).  An operator symbol  (-)  is
  488.      said to:
  489.  
  490.        o  group to the left  if "x - y - z" is treated as "(x - y) - z"
  491.  
  492.        o  group to the right if "x - y - z" is treated as "x - (y - z)"
  493.  
  494.      A third possibility is that an expression of the form "x - y -  z"
  495.      is to be treated as ambiguous and will  be  flagged  as  a  syntax
  496.      error.   In  this  case  we  say  that   the   operator   (-)   is
  497.      non-associative.
  498.  
  499.      The standard approach in Gofer is to treat (-) as grouping to  the
  500.      left so that "1 - 2 - 3" will actually be treated as "(1-2)-3".
  501.  
  502. By  default,  every  operator   symbol   in   Gofer   is   treated   as
  503. non-associative with precedence 9.  These values can be  changed  by  a
  504. declaration of one of the following forms:
  505.  
  506.     infixl digit ops      to declare operators which group to the left
  507.     infixr digit ops      to declare operators which group to the right
  508.     infix  digit ops      to declare non-associative operators
  509.  
  510. In each of these declarations ops represents a  list  of  one  or  more
  511. operator symbols separated by commas and digit is an integer between  0
  512. and 9 which gives the precedence value for each of the listed  operator
  513. symbols.  The precedence digit may be omitted in which case a value  of
  514. 9 is assumed.  There are a number of restrictions on the use  of  these
  515. declarations:
  516.  
  517.   o  Operator  declarations  can  only  appear  in  files  of  function
  518.      definitions which are loaded into Gofer; they  cannot  be  entered
  519.      directly whilst using the Gofer interpreter.
  520.  
  521.   o  At most one operator declaration is permitted for  any  particular
  522.      operator symbol (even if repeated  declarations  all  specify  the
  523.      same precedence and grouping as the original declaration).
  524.  
  525.   o  Any file containing a declaration for an operator  precedence  and
  526.      grouping must also contain  a  (top-level)  declaration  for  that
  527.      operator.
  528.  
  529. In theory, it is possible to use an operator declaration at  any  point
  530. in a file of definitions.  In practice, it is sensible to  ensure  that
  531. each operator is declared before  the  symbol  is  used.   One  way  to
  532. guarantee this is to place all operator declarations at  the  beginning
  533. of the file [this condition is enforced in Haskell].  Note  that  until
  534. an operator declaration for a particular  symbol  is  encountered,  any
  535. occurrence of that symbol will be treated as a non-associative operator
  536. with precedence 9.
  537.  
  538. The following operator declarations are taken from the standard prelude:
  539.  
  540.     -- Operator precedence table
  541.  
  542.     infixl 9 !!
  543.     infixr 9 .
  544.     infixr 8 ^
  545.     infixl 7 *
  546.     infix  7 /, `div`, `rem`, `mod`
  547.     infixl 6 +, -
  548.     infix  5 \\
  549.     infixr 5 ++, :
  550.     infix  4 ==, /=, <, <=, >=, >
  551.     infix  4 `elem`, `notElem`
  552.     infixr 3 &&
  553.     infixr 2 ||
  554.  
  555. and their use is illustrated by the following examples:
  556.  
  557.  Expression:     Equivalent to:   Reasons:
  558.  -----------     --------------   --------
  559.  1 + 2 - 3       (1 + 2) - 3      (+) and (-) have the same  precedence
  560.                                   and group to the left.
  561.  x : ys ++ zs    x : (ys ++ zs)   (:) and (++) have the same precedence
  562.                                   and group to the right
  563.  x == y || z     (x == y) || z    (==) has higher precedence than (||).
  564.  3 * 4 + 5       (3 * 4) + 5      (*) has higher precedence than (+).
  565.  y `elem` z:zs   y `elem` (z:zs)  (:) has higher precedence than elem.
  566.  12 / 6 / 3      syntax error     ambiguous  use  of  (/);  could  mean
  567.                                   either (12/6)/3 or 12/(6/3).
  568.  
  569. Note that function application always binds more tightly than any infix
  570. operator symbol.  For example, the expression "f x + g y" is equivalent
  571. to "(f x) + (g y)".  Another example which often causes problems is the
  572. expression  "f x + 1",  which is treated as "(f x)  +  1"  and  not  as
  573. "f (x+1)" as is sometimes expected.
  574. .pa
  575. .co-------------------------------------------------------------------|
  576. .>ch07
  577. .ST 7. BUILT-IN TYPES
  578.  
  579. An important part of Gofer is the type system which is used  to  detect
  580. errors  in  expressions  and  function  definitions.    Starting   with
  581. primitive expressions such as numeric constants, Gofer assigns  a  type
  582. to each expression that describes the kind of value represented by  the
  583. expression.
  584.  
  585. In  general  we write  object :: type  to indicate  that  a  particular
  586. expression has the indicated type.  For example:
  587.  
  588.     42   :: Int         indicating that  42  is an  integer (Int is the
  589.                         name for the type of integer values).
  590.  
  591.     fact :: Int -> Int  indicating  that  "fact"  is a  function  which
  592.                         takes  an  integer  argument  and  returns   an
  593.                         integer value (its factorial).
  594.  
  595. The most important property of the type system is that it  is  possible
  596. to determine the type of an expression without having to  evaluate  it.
  597. For example, the information given above  is  sufficient  to  determine
  598. that fact 42 :: Int without needing to calculate 42! first.
  599.  
  600. Gofer has a wide range of built-in types, described  in  the  following
  601. sections.  In addition, Gofer also includes facilities for defining new
  602. types as well as types acting as  abbreviations  for  complicated  type
  603. expressions as described in section 11.
  604.  
  605.  
  606. .ST 7.1  Functions
  607. --------------
  608. If t1 and t2 are types then t1 -> t2 is the type of a  function  which,
  609. given an argument of type t1 produces a result of type t2.  A  function
  610. of type t1 -> t2 is said to have argument type t1 and result type t2.
  611.  
  612. In mathematics, the result of applying a function f to an argument x is
  613. traditionally written as f(x).  In many situations,  these  parentheses
  614. are unnecessary and may be omitted when using Gofer.
  615.  
  616. e.g. if f :: t1 -> t2 and x :: t1 then f x is the result of applying
  617.      f to x and has type t2.
  618.  
  619.  
  620. If t1, t2, ..., tn are type expressions then:
  621.  
  622.                    t1 -> t2 -> ... -> tn
  623.  
  624. can be used as an abbreviation for the type:
  625.  
  626.                t1 -> (t2 -> ( ... -> tn) ...)
  627.  
  628. In a similar way, an expression of the form f x1 x2 ... xn is simply an
  629. abbreviation for the expression ( ... ((f x1) x2) ... xn).
  630.  
  631. These two conventions allow us to deal with functions taking more  than
  632. one argument rather elegantly.  For example, the type of  the  addition
  633. function (+) is:
  634.                        Int -> Int -> Int
  635.  
  636. In other words, "(+)" is a function which takes an integer argument and
  637. returns a value of type (Int -> Int).  For  example,  "(+)  5"  is  the
  638. function which takes an integer value n and returns the  value  of  the
  639. integer n plus 5.  Hence "(+) 5 4", which is equivalent  to  "5  +  4",
  640. evaluates to the integer 9 as expected.
  641.  
  642.  
  643. .ST 7.2  Booleans
  644. -------------
  645. Represented by the type "Bool", there are two boolean values written as
  646. "True" and "False".   The  standard  prelude  includes  several  useful
  647. functions for manipulating boolean values:
  648.  
  649.     (&&), (||) :: Bool -> Bool -> Bool
  650.  
  651.         The value of the expression b && d is True if and only if  both
  652.         b and d are True.  If b is False then d is not evaluated.
  653.  
  654.         The value of the expression b || d is True if either of b or  d
  655.         is True.  If b is True then d is not evaluated.
  656.  
  657.     not  :: Bool -> Bool
  658.  
  659.         The value of the expression not b is the opposite boolean value
  660.         to that of b; not True = False, not False = True.
  661.  
  662. Gofer includes a special form of `conditional expression' which enables
  663. an expression to select between two alternatives according to the value
  664. of a boolean expression:
  665.  
  666.                      if b then t else f 
  667.  
  668. is an expression which is equivalent to t if b evaluates to True, or to
  669. f if b evaluates to False.  Note that an expression  of  this  form  is
  670. only acceptable if b is an expression of type Bool and if the types  of
  671. t and f are the same, in which case the whole expression also has  that
  672. type.
  673.  
  674.  
  675. .ST 7.3  Integers
  676. -------------
  677. Represented by the type "Int", the integer type includes both  positive
  678. and negative integers such as -273, 0  and  383.   Like  many  computer
  679. systems, the range of integer values that can be used is restricted and
  680. calculations using large positive  or  negative  numbers  may  lead  to
  681. (undetected) overflow.
  682.  
  683. A wide range of operators and functions are  defined  in  the  standard
  684. prelude for use with integers:
  685.  
  686.     (+)     addition.
  687.     (*)     multiplication.
  688.     (-)     subtraction.
  689.     (^)     raise to power.
  690.     negate  unary negation.  An expression of the form "-x" is treated
  691.             as the expression "negate x".
  692.     (/)     integer division.
  693.     div        "        "
  694.     rem     remainder, related to integer division by the law:
  695.                      (x `div` y)*y + (x `rem` y) == x
  696.     mod     modulo, like remainder except that the modulo has the same
  697.             sign as the divisor.
  698.     odd     returns True if argument is odd, False otherwise.
  699.     even    returns True if argument is even, False otherwise.
  700.     gcd     returns the greatest common divisor of its two arguments.
  701.     lcm     returns the least common multiple of its two arguments.
  702.     abs     returns the absolute value of its argument.
  703.     signum  returns -1, 0 or 1 indicating that its argument is negative,
  704.             zero or positive respectively.
  705.  
  706. The  less  familiar  operators  are  illustrated   by   the   following
  707. identities:
  708.  
  709.      3^4 == 81,          7 `div` 3 == 2,      even 23 == False
  710.      7 `rem` 3 == 1,    -7 `rem` 3 == -1,     7 `rem` -3 == 1
  711.      7 `mod` 3 == 1,    -7 `mod` 3 == 2,      7 `mod` -3 == -2
  712.      gcd 32 12 == 4,    abs (-2) == 2,        signum 12 == 1
  713.  
  714.  
  715. .ST 7.4  Floating point numbers
  716. ---------------------------
  717. Represented by the type "Float", elements of this type can be  used  to
  718. represent fractional values  as  well  as  very  large  or  very  small
  719. quantities.  Such values are however usually only accurate to  a  fixed
  720. number of digits and rounding errors may  occur  in  some  calculations
  721. making significant use of floating point quantities.  A  numeric  value
  722. in an input expression will only be treated as a floating point  number
  723. if it either includes a decimal point such as 3.14159, or if the number
  724. is too large to be stored as a value of type Int.  Scientific  notation
  725. may also be used to enter floating point quantities; for example  1.0e3
  726. is equivalent to 1000.0, whilst 5.0e-2 is equivalent to 0.05.
  727.  
  728. [N.B. floating point numbers are not included in all implementations of
  729. Gofer].
  730.  
  731.  
  732. .ST 7.5  Characters
  733. ---------------
  734. Represented by  the  type  "Char",  elements  of  this  type  represent
  735. individual characters such as those entered at a  keyboard.   Character
  736. values  are  written  as  single  characters  enclosed  by   apostrophe
  737. characters: e.g. 'a',  '0',  'Z'.   Some  special  characters  must  be
  738. entered using an `escape code'; each of these begins with  a  backslash
  739. character '\', followed  by  one  or  more  characters  to  select  the
  740. required character.  Some of the most useful escape codes are:
  741.  
  742.      '\\'             backslash
  743.      '\''             apostrophe
  744.      '\"'             double quote
  745.      '\n'             newline
  746.      '\b' or '\BS'    backspace
  747.      '\DEL'           delete
  748.      '\t' or '\HT'    tab
  749.      '\a' or '\BEL'   alarm (bell)
  750.      '\f' or '\FF'    formfeed
  751.  
  752. Additional escape characters include:
  753.  
  754.      '\^c'            control character, where c is replaced by
  755.                       one of the characters:
  756.                          "@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_"
  757.                       For example, '\^A' represents control-A
  758.  
  759.      '\number'        representing the character with ASCII value
  760.                       specified by the given decimal 'number'.
  761.  
  762.      '\onumber'       representing the character with ASCII value
  763.                       specified by the given octal 'number'.
  764.  
  765.      '\xnumber'       representing the character with ASCII value
  766.                       specified by the given 'hexadecimal' number.
  767.  
  768.      '\name'          named ASCII control character, where
  769.                       `name' is replaced by one of the standard
  770.                       ascii names e.g. `\DC3`.
  771.  
  772. In contrast with  some  common  languages  (such  as  C,  for  example)
  773. character values are quite distinct from integers; however the standard
  774. prelude does include functions:
  775.  
  776.                    ord :: Char -> Int
  777.                    chr :: Int -> Char
  778.  
  779. which enable you to map a character to its corresponding  ASCII  value,
  780. or from an ASCII value to the corresponding character:
  781.  
  782.     ? ord 'a'
  783.     97
  784.     (2 reductions, 6 cells)
  785.     ? chr 65
  786.     'A'
  787.     (2 reductions, 7 cells)
  788.     ?         
  789.  
  790.  
  791. .ST 7.6  Lists
  792. ----------
  793. If a is a type then [a] is the type whose elements are lists of  values
  794. of type a.  There are several ways of writing list expressions:
  795.  
  796.   o   The simplest list of any type is the empty list, written [].
  797.  
  798.   o   Non-empty lists  can be constructed either by  explicitly listing
  799.       the members of the list (for example: [1,3,10]) or  by  adding  a
  800.       single element onto the front  of  another  list  using  the  (:)
  801.       operator (pronounced "cons").  These notations are equivalent:
  802.  
  803.        [1,3,10]  =  1 : [3,10]  =  1 : 3 : [10]  =  1 : 3 : 10 : []
  804.  
  805.       (the (:) operator groups to the right so 1 :  3  :  10  :  []  is
  806.       equivalent to (1:(3:(10:[]))) -- a list whose first element is 1,
  807.       second element is 3 and last element is 10).
  808.  
  809. The  standard  prelude  includes  a  wide  range   of   functions   for
  810. calculations involving lists.  For example:
  811.  
  812.   o  length xs  returns the number of elements in the list xs.
  813.   o  xs ++ ys   returns the list of elements in xs followed by the
  814.                 elements in ys
  815.   o  concat xss returns the list of elements in each of the lists in
  816.                 xss
  817.   o  map f xs   returns the list of values obtained by applying the
  818.                 function f to each of the values in the list xs in turn.
  819.  
  820. Here are some examples using these functions:
  821.  
  822.     ? length [1,3,10]
  823.     3
  824.     (15 reductions, 28 cells)
  825.  
  826.     ? [1,3,10] ++ [2,6,5,7]
  827.     [1, 3, 10, 2, 6, 5, 7]
  828.     (19 reductions, 77 cells)
  829.  
  830.     ? concat [[1], [2,3], [], [4,5,6]]
  831.     [1, 2, 3, 4, 5, 6]
  832.     (29 reductions, 93 cells)
  833.  
  834.     ? map ord ['H', 'e', 'l', 'l', 'o']
  835.     [72, 101, 108, 108, 111]
  836.     (22 reductions, 73 cells)
  837.  
  838.     ?
  839.  
  840. Note that all of the elements in a list must be of the  same  type,  so
  841. that an expression such as ['a', 2, False] is not permitted.
  842.  
  843. [ASIDE: At this point  it  might  be  useful  to  mention  an  informal
  844. convention that is used by a  number  of  functional  programmers  when
  845. choosing names for variables  representing  elements  of  lists,  lists
  846. themselves, lists of lists and  so  on.   If  for  example,  a  typical
  847. element of a list is called x, then it is often useful to use the  name
  848. xs for a list of such values, suggesting that a list contains a  number
  849. of "x"s.  Similarly, a list of lists might be  called  xss.   Once  you
  850. have understood this convention it  is  much  easier  to  remember  the
  851. relationship between the variables in the  expression  (x:xs)  than  it
  852. would be if different names had been used such as (a:b).]
  853.  
  854.  
  855. .ST 7.7  Strings
  856. ------------
  857. A string is treated as a list of characters  and  the  type  String  is
  858. simply an abbreviation for the type [Char].   Strings  are  written  as
  859. sequences of characters enclosed between  speech  marks.   All  of  the
  860. escape codes that can be used for characters may  also  be  used  in  a
  861. string:
  862.  
  863.     ? "hello, world"
  864.     hello, world
  865.     (0 reductions, 13 cells)
  866.  
  867.     ? "hello\nworld"
  868.     hello
  869.     world
  870.     (0 reductions, 12 cells)
  871.     ?
  872.  
  873. In addition, strings may contain the escape sequence "\&" which can  be
  874. used to separate otherwise  ambiguous  pairs  of  characters  within  a
  875. string:
  876.  
  877.     e.g.  "\123h"   represents the string ['\123', 'h']
  878.           "\12\&3h" represents the string ['\12', '3', 'h']
  879.  
  880. A string expression may be spread over a number of lines using a gap --
  881. a non-empty sequence of space, tab and new line characters enclosed  by
  882. backslash characters:
  883.  
  884.     ? "hell\   \o"
  885.     hello
  886.     (0 reductions, 6 cells)
  887.     ? 
  888.  
  889. Notice that strings are printed  differently from other  values,  which
  890. gives the programmer complete control over the  format  of  the  output
  891. produced by a program.  The only values that Gofer can in fact  display
  892. on the terminal are strings.  If the type of an expression entered into
  893. Gofer is equivalent to String then the expression is  printed  directly
  894. by evaluating and printing each character  in  the  list  in  sequence.
  895. Otherwise, the expression to  be  evaluated,  e,  is  replaced  by  the
  896. expression show' e where show' is a built-in function (defined as  part
  897. of the standard prelude)  which  converts  any  value  to  a  printable
  898. representation.  The  only way of printing a  string value  in the same
  899. way as any other value is by explicitly using the show' function:
  900.  
  901.     ? show' "hello"
  902.     "hello"
  903.     (7 reductions, 24 cells)
  904.     ?
  905.  
  906. The careful reader may have been puzzled by  the  fact  the  number  of
  907. reductions used in the first three examples above was zero.  This is in
  908. fact quite correct since these expressions are constants and no further
  909. evaluation can be carried out.  For constant expressions of  any  other
  910. type there will always be at least one reduction needed  to  print  the
  911. value since the constant  must  first  be  translated  to  a  printable
  912. representation using the show' function.
  913.  
  914. Because strings are represented as lists  of  characters,  all  of  the
  915. standard prelude functions for manipulating lists can also be used with
  916. strings:
  917.  
  918.     ? length "Hello"
  919.     5
  920.     (22 reductions, 36 cells)
  921.  
  922.     ? "Hello, " ++ "world"
  923.     Hello, world
  924.     (8 reductions, 37 cells)
  925.  
  926.     ? concat ["super","cali","fragi","listic"]
  927.     supercalifragilistic
  928.     (29 reductions, 101 cells)
  929.  
  930.     ? map ord "Hello"
  931.     [72, 101, 108, 108, 111]
  932.     (22 reductions, 69 cells)
  933.  
  934.     ? 
  935.  
  936.  
  937. .ST 7.8  Tuples and the unit type
  938. -----------------------------
  939. If t1, t2, ..., tn are types and n>=2, then there is a type of n-tuples
  940. written (t1, t2, ..., tn) whose elements are also written in  the  form
  941. (x1, x2, ..., xn) where the expressions x1, x2, ..., xn have types  t1,
  942. t2, ..., tn respectively.
  943.  
  944.     e.g.  (1, [2], 3)   :: (Int, [Int], Int)
  945.           ('a', False)  :: (Char, Bool)
  946.           ((1,2),(3,4)) :: ((Int, Int), (Int, Int))
  947.  
  948. Note that, unlike lists, the elements in a  tuple  may  have  different
  949. types, although the number of elements in the tuple is fixed.
  950.  
  951. The unit type is written () and has a  single  element  which  is  also
  952. written as ().  The unit type is of particular interest in  theoretical
  953. treatments of the type system of Gofer, although you  may  occasionally
  954. find a use for it in practical programs.
  955. .pa
  956. .co-------------------------------------------------------------------|
  957. .>ch08
  958. .ST 8. ERRORS
  959.  
  960. .ST 8.1  Errors detected on input
  961. -----------------------------
  962. After an expression has been entered, but before any attempt is made to
  963. evaluate it, Gofer carries out a number of checks to make sure that the
  964. expression that you typed does not contain any errors.  Here  are  some
  965. examples of the kind of problem that might occur:
  966.  
  967.   o  Syntax errors.  The most common situation in which this happens is
  968.      when  you  make  a  typing  mistake,  either  leaving   out   some
  969.      characters, or perhaps pressing the wrong keys  instead.   In  the
  970.      following example, the user has missed out a `[' character:
  971.  
  972.          ? sum 1..100]
  973.          ERROR: Syntax error in input (unexpected `..')
  974.          ?
  975.  
  976.   o  Undefined variables.  This happens when you  enter  an  expression
  977.      using a variable or function name that is not defined  in  any  of
  978.      the files of definitions loaded into Gofer.  This can  often  mean
  979.      that you have misspelt the name of a function, or that  the  files
  980.      defining a function have not yet been loaded.  For example:
  981.  
  982.          ? sum [1..n]
  983.          ERROR: Undefined variable "n"
  984.          ? 
  985.  
  986.   o  Type errors.  Certain  expressions  are  sensible  only  when  the
  987.      functions used in those expressions are applied to values  of  the
  988.      appropriate type.  For example, whilst the factorial function  can
  989.      be used to calculate the factorial of an integer,  it  is  clearly
  990.      meaningless to try to  determine  the  factorial  of  a  character
  991.      value.  This kind of problem can be detected using  the  types  of
  992.      the components of an expression.  In the expression "fact 'A'", we
  993.      can see that the argument 'A' has type Char which does  not  match
  994.      the argument type Int of the factorial function.  This error  will
  995.      be detected by Gofer if you try to evaluate the expression:
  996.  
  997.          ? fact 'A'
  998.          ERROR: Type error in application
  999.          *** expression     : fact 'A'
  1000.          *** term           : 'A'
  1001.          *** type           : Char
  1002.          *** does not match : Int
  1003.  
  1004.          ?
  1005.  
  1006.  
  1007. .ST 8.2  Errors during evaluation
  1008. -----------------------------
  1009. If no errors are detected in an input expression, Gofer then begins  to
  1010. evaluate that expression.  Despite all of the checks that  are  carried
  1011. out before the evaluation begins, it is still possible for an error  to
  1012. occur during the evaluation of an expression.   A  typical  example  of
  1013. this is an attempt to divide a number by zero.   In  this  case,  Gofer
  1014. prints the part of the  expression  being  evaluated  that  caused  the
  1015. error, surrounded by braces `{' and `}':
  1016.  
  1017.     ? 3/0
  1018.     {primDivInt 3 0}
  1019.     (4 reductions, 30 cells)
  1020.     ? 
  1021.  
  1022. [The function "primDivInt" which appears here is a  primitive  function
  1023. used to divide  one  integer  (its  first  argument)  by  another  (the
  1024. second)].  If an error occurs in just one part of  an  expression, only
  1025. the part causing the problem will be displayed:
  1026.  
  1027.     ? 4 + (5/0)
  1028.     {primDivInt 5 0}
  1029.     (5 reductions, 32 cells)
  1030.     ? 
  1031.  
  1032. A standard function called "error" is defined in the  standard  prelude
  1033. which is often useful for ensuring that appropriate error messages  are
  1034. produced when an error occurs:
  1035.  
  1036.     ? error "Problem has occurred"
  1037.     {error "Problem has occurred"}
  1038.     (23 reductions, 99 cells)
  1039.     ? 
  1040. .pa
  1041. .co-------------------------------------------------------------------|
  1042. .>ch09
  1043. .ST 9. MORE ABOUT VALUE DECLARATIONS
  1044.  
  1045. .ST 9.1  Simple pattern matching
  1046. ----------------------------
  1047. Although the Gofer standard prelude includes many useful functions, you
  1048. will usually need to define a collection of new functions for  specific
  1049. problems and calculations.  The declaration of a function  "f"  usually
  1050. takes the form of a number of equations of the form:
  1051.  
  1052.             f <pat1> <pat2> ... <patn>  =   <rhs>
  1053.  
  1054. (or an equivalent expression, if "f"  is  written  as  by  an  operator
  1055. symbol).   Each  of  the  expressions  <pat1>,  <pat2>,   ...,   <patn>
  1056. represents an argument to the function "f" and is called  a  `pattern'.
  1057. The number of such arguments is called the arity of  "f".   If  "f"  is
  1058. defined by more than one equation then they must  be  entered  together
  1059. and each one must give the same arity for "f".
  1060.  
  1061. When a function is defined by more than one equation, it  will  usually
  1062. be necessary to evaluate one or more of the arguments to  the  function
  1063. to  determine  which  equation  applies.   This   process   is   called
  1064. `pattern-matching'.  In all of the previous examples we have used  only
  1065. the simplest kind of pattern -- a variable.  As  an  example,  consider
  1066. the factorial function defined in section 5:
  1067.  
  1068.     fact n = product [1..n]
  1069.  
  1070. If we then wish to evaluate the expression "fact 6" we first match  the
  1071. expression "6" against the pattern "n" and then evaluate the expression
  1072. obtained from "product [1..n]" by replacing the variable "n"  with  the
  1073. expression "6".  The process of matching the arguments  of  a  function
  1074. against the patterns in its definition and obtaining another expression
  1075. to be evaluated is called a `reduction'.  Using Gofer, it  is  easy  to
  1076. verify that the evaluation of "fact 6" takes one  more  reduction  than
  1077. that of "product [1..6]":
  1078.  
  1079.     ? fact 6
  1080.     720
  1081.     (57 reductions, 85 cells)
  1082.     ? product [1..6]
  1083.     720
  1084.     (56 reductions, 85 cells)
  1085.     ? 
  1086.  
  1087. Many kinds of constants such as the boolean values True and  False  can
  1088. also be used in  patterns,  as  in  the  following  definition  of  the
  1089. function "not" taken from the standard prelude:
  1090.  
  1091.     not True  = False
  1092.     not False = True
  1093.  
  1094. In order to determine the value of an expression of the form  "not  b",
  1095. we must first evaluate the expression "b".  If  the  result  is  "True"
  1096. then we use the first equation  and  the  value  of  "not  b"  will  be
  1097. "False".  If the value of "b" is "False", then the second  equation  is
  1098. used and the value of "not b" will be "True".
  1099.  
  1100. Other constants, including integers, characters and strings may also be
  1101. used in patterns.  For example, if we define a function "hello" by:
  1102.  
  1103.     hello "Mark"  =  "Howdy"
  1104.     hello name    =  "Hello " ++ name ++ ", nice to meet you!"
  1105.  
  1106. then:
  1107.  
  1108.     ? hello "Mark"
  1109.     Howdy
  1110.     (1 reduction, 12 cells)
  1111.     ? hello "Fred"
  1112.     Hello Fred, nice to meet you!
  1113.     (13 reductions, 66 cells)
  1114.     ?
  1115.  
  1116. Note that the  order  in  which  the  equations  are  written  is  very
  1117. important because Gofer always uses the first applicable equation.   If
  1118. instead we had defined the function with the equations:
  1119.  
  1120.     hello name    =  "Hello " ++ name ++ ", nice to meet you!"
  1121.     hello "Mark"  =  "Howdy"
  1122.  
  1123. then the results obtained using this function would have been a  little
  1124. different:
  1125.  
  1126.     ? hello "Mark"
  1127.     Hello Mark, nice to meet you!
  1128.     (13 reductions, 66 cells)
  1129.     ? hello "Fred"
  1130.     Hello Fred, nice to meet you!
  1131.     (13 reductions, 66 cells)
  1132.     ?
  1133.  
  1134. There are a number of other useful kinds of pattern, some of which  are
  1135. illustrated by the following examples:
  1136.  
  1137.   o  Wildcard:       _        matches  any value  at all;  it is like a
  1138.                               variable pattern, except that there is no
  1139.                               way of referring to the matched value.
  1140.  
  1141.   o  Tuples:         (x,y)    matches a  pair  whose  first  and second
  1142.                               elements are called x and y respectively.
  1143.  
  1144.   o  Lists:          [x]      matches a list with precisely one element
  1145.                               called x.
  1146.                      [_,2,_]  matches  a   list  with   precisely three
  1147.                               elements,  the  second  of  which  is the
  1148.                               integer 2.
  1149.                      []       matches the empty list.
  1150.                      (x:xs)   matches a non-empty  list with head x and
  1151.                               tail xs.
  1152.  
  1153.   o  As patterns:    p@(x,y)  matches a  pair  whose  first and  second
  1154.                               components  are  called  x  and  y.   The
  1155.                               complete pair can  also  be  referred  to
  1156.                               directly as p.
  1157.  
  1158.   o  (n+k) patterns: (m+1)    matches an integer value  greater than or
  1159.                               equal to 1.  The value referred to by the
  1160.                               variable m is one  less  than  the  value
  1161.                               matched.
  1162.  
  1163. A further kind of pattern (called an irrefutable pattern) is introduced
  1164. in section 9.11.
  1165.  
  1166. Note that no variable name can be used more than once on the left  hand
  1167. side of each equation in a function definition.  The following example:
  1168.  
  1169.     areTheyTheSame x x = True 
  1170.     areTheyTheSame _ _ = False 
  1171.  
  1172. will not be accepted by the Gofer system, but should instead be defined
  1173. using the notation of guards introduced in the next section:
  1174.  
  1175.     areTheyTheSame x y
  1176.             | x==y      = True
  1177.             | otherwise = False
  1178.  
  1179.  
  1180. .ST 9.2  Guarded equations
  1181. ----------------------
  1182. Each of the equations in a function  definition  may  contain  `guards'
  1183. which require  certain conditions  on  the  values  of  the  function's
  1184. arguments to be met.  As an example, here is a function which uses  the
  1185. standard prelude function even :: Int -> Bool to determine whether  its
  1186. argument is an even integer or not, and returns the  string  "even"  or
  1187. "odd" as appropriate:
  1188.  
  1189.     oddity n | even n    = "even"
  1190.              | otherwise = "odd"
  1191.  
  1192. In general, an equation using guards takes the form:
  1193.  
  1194.     f x1 x2 ... xn | condition1  =  e1
  1195.                    | condition2  =  e2
  1196.                    .
  1197.                    . 
  1198.                    | conditionm  =  em
  1199.  
  1200. This equation is used by evaluating each  of  the  conditions  in  turn
  1201. until one of them evaluates to "True", in which case the value  of  the
  1202. function is given by the corresponding expression e on the  right  hand
  1203. side of the `=' sign.  In Gofer, the variable "otherwise" is defined to
  1204. be equal to "True", so that writing "otherwise" as the condition  in  a
  1205. guard means that the corresponding expression will always be used if no
  1206. previous guard has been satisfied.
  1207.  
  1208. [ASIDE: in the notation of [1], the above examples would be written as:
  1209.  
  1210.     oddity n        =  "even",   if even n
  1211.                     =  "odd",    otherwise
  1212.  
  1213.     f x1 x2 ... xn  = e1,     if condition1
  1214.                     = e2,     if condition2
  1215.                       .
  1216.                       .
  1217.                     = em,     if conditionm
  1218.  
  1219. Translation between the two notations is relatively straightforward.]
  1220.  
  1221.  
  1222. .ST 9.3  Local definitions
  1223. ----------------------
  1224. Function definitions may include local definitions for variables  which
  1225. can be used both in guards and on the right hand side of  an  equation.
  1226. Consider the following function which calculates the number of distinct
  1227. real roots for a quadratic equation of the form a*x*x + b*x + c = 0:
  1228.  
  1229.     numberOfRoots a b c | discr>0   =  2
  1230.                         | discr==0  =  1
  1231.                         | discr<0   =  0
  1232.                           where discr = b*b - 4*a*c
  1233.  
  1234. [ASIDE: The operator (==) is used to test whether two values are  equal
  1235. or not.  You should take care not to confuse this with the  single  `='
  1236. sign used in function definitions].
  1237.  
  1238. Local definitions can also be introduced at an arbitrary  point  in  an
  1239. expression using an expression of the form:
  1240.  
  1241.                   let <decls> in <expr>
  1242.  
  1243. For example:
  1244.  
  1245.     ? let x = 1 + 4 in x*x + 3*x + 1
  1246.     41
  1247.     (8 reductions, 15 cells)
  1248.     ? let p x = x*x + 3*x + 1  in  p (1 + 4)
  1249.     41
  1250.     (7 reductions, 15 cells)
  1251.     ?
  1252.  
  1253.  
  1254. .ST 9.4  Recursion with integers
  1255. ----------------------------
  1256. Recursion  is  a  particularly  important  and  powerful  technique  in
  1257. functional programming which is useful for defining functions involving
  1258. a wide range of datatypes.  In this section, we describe one particular
  1259. application of recursion to give  an  alternative  definition  for  the
  1260. factorial function from section 5.
  1261.  
  1262. Suppose that we wish to calculate the factorial of a given  integer  n.
  1263. We can split the problem up into two special cases:
  1264.  
  1265.   o  If n is zero then the value of n! is 1.
  1266.  
  1267.   o  Otherwise, n!  = 1 * 2 * ... * (n-1) * n = (n-1)! * n  and  so  we
  1268.      can calculate the value of n! by calculating the value  of  (n-1)!
  1269.      and then multiplying it by n.
  1270.  
  1271. This process can be expressed directly in  Gofer  using  a  conditional
  1272. expression:
  1273.  
  1274.     fact1 n  =  if n==0 then 1 else n * fact1 (n-1)
  1275.  
  1276. This definition may seem rather circular; in  order  to  calculate  the
  1277. value of n!, we must first calculate (n-1)!, and unless n  is  1,  this
  1278. requires the calculation of (n-2)! etc...  However, if  we  start  with
  1279. some positive value for the variable n, then we will  eventually  reach
  1280. the case where the value of 0! is required -- and this does not require
  1281. any further calculation.  The following diagram illustrates how  6!  is
  1282. evaluated using "fact1":
  1283.  
  1284.     fact1 6  ==>  6 * fact1 5
  1285.              ==>  6 * (5 * fact1 4)
  1286.              ==>  6 * (5 * (4 * fact1 3))
  1287.              ==>  6 * (5 * (4 * (3 * fact1 2)))
  1288.              ==>  6 * (5 * (4 * (3 * (2 * fact1 1))))
  1289.              ==>  6 * (5 * (4 * (3 * (2 * (1 * fact1 0)))))
  1290.              ==>  6 * (5 * (4 * (3 * (2 * (1 * 1)))))
  1291.              ==>  6 * (5 * (4 * (3 * (2 * 1))))
  1292.              ==>  6 * (5 * (4 * (3 * 2)))
  1293.              ==>  6 * (5 * (4 * 6))
  1294.              ==>  6 * (5 * 24)
  1295.              ==>  6 * 120
  1296.              ==>  720
  1297.  
  1298. Incidentally, there are several other ways  of  writing  the  recursive
  1299. definition of "fact1" above in Gofer.  For example, using guards:
  1300.  
  1301.     fact2 n
  1302.       | n==0        =  1
  1303.       | otherwise   =  n * fact2 (n-1)
  1304.  
  1305. or using pattern matching with an integer constant:
  1306.  
  1307.     fact3 0         =  1
  1308.     fact3 n         =  n * fact3 (n-1)
  1309.  
  1310. Which of these you use is largely a matter of personal taste.
  1311.  
  1312. Yet another style of definition uses the (n+k)  patterns  mentioned  in
  1313. section 9.1:
  1314.  
  1315.     fact4 0         =  1
  1316.     fact4 (n+1)     =  (n+1) * fact4 n
  1317.  
  1318. which is equivalent to:
  1319.  
  1320.     fact5 n | n==0  =  1
  1321.             | n>=1  =  n * fact5 (n-1)
  1322.  
  1323. [COMMENT: Although each of the above definitions gives the same  result
  1324. as the original "fact" function  for  each  non-negative  integer,  the
  1325. functions can still be distinguished by the values obtained  when  they
  1326. are applied to negative integers:
  1327.  
  1328.   o  "fact (-1)" evaluates to the integer 1.
  1329.   o  "fact1 (-1)" causes Gofer to enter an infinite loop, which is only
  1330.      eventually terminated when Gofer runs out of `stack space'.
  1331.   o  "fact4 (-1)" causes an evaluation error and prints the
  1332.       message {fact4 (-1)} on the screen.
  1333.  
  1334. To most people, this suggests that the definition of "fact4" is perhaps
  1335. preferable to that of either "fact" or "fact1" as it neither gives  the
  1336. wrong answer  without  allowing  this  to  be  detected  nor  causes  a
  1337. potentially non-terminating computation.]
  1338.  
  1339.  
  1340. .ST 9.5  Recursion with lists
  1341. -------------------------
  1342. The same kind of  technique  that  can  be  used  to  define  recursive
  1343. functions with integers can also be used to define recursive  functions
  1344. on lists.  As an example, suppose that we wish to define a function  to
  1345. calculate the length of  a  list.   As  the  standard  prelude  already
  1346. includes such a function called "length", we  will  call  the  function
  1347. developed here "len" to avoid any conflict.  Now suppose that  we  wish
  1348. to find the length of a given list.  There are two cases to consider:
  1349.  
  1350.   o  If the list is empty then it has length 0
  1351.  
  1352.   o  Otherwise, it is non-empty and can be written in the  form  (x:xs)
  1353.      for some element x and some list xs.  Thus the  original  list  is
  1354.      one element longer than xs, and so has length 1 + len xs.
  1355.  
  1356. Writing these two cases out leads directly to the following definition:
  1357.  
  1358.     len []      =  0
  1359.     len (x:xs)  =  1 + len xs
  1360.  
  1361. The following diagram illustrates the way that  this  function  can  be
  1362. used to determine the length of the list [1,2,3,4] (remember that  this
  1363. is just an abbreviation for 1 : 2 : 3 : 4 : []):
  1364.  
  1365.     len [1,2,3,4]  ==>  1 + len [2,3,4]
  1366.                    ==>  1 + (1 + len [3,4])
  1367.                    ==>  1 + (1 + (1 + len [4]))
  1368.                    ==>  1 + (1 + (1 + (1 + len [])))
  1369.                    ==>  1 + (1 + (1 + (1 + 0)))
  1370.                    ==>  1 + (1 + (1 + 1))
  1371.                    ==>  1 + (1 + 2)
  1372.                    ==>  1 + 3
  1373.                    ==>  4
  1374.  
  1375. As  further  examples,  you  might  like  to  look  at  the   following
  1376. definitions which use similar ideas to define the functions product and
  1377. map introduced in earlier sections:
  1378.  
  1379.     product []     = 1
  1380.     product (x:xs) = x * product xs
  1381.  
  1382.     map f []      =  []
  1383.     map f (x:xs)  =  f x : map f xs
  1384.  
  1385.  
  1386. .ST 9.6  Lazy evaluation
  1387. --------------------
  1388. Gofer evaluates expressions using a technique  sometimes  described  as
  1389. `lazy evaluation' which means that:
  1390.  
  1391.   o  No expression is evaluated until its value is needed.
  1392.  
  1393.   o  No  shared  expression  is  evaluated  more  than  once;  if   the
  1394.      expression is ever evaluated then the result is shared between all
  1395.      those places in which it is used.
  1396.  
  1397. The first of these ideas is illustrated by the following function:
  1398.  
  1399.     ignoreArgument x = "I didn't need to evaluate x"
  1400.  
  1401. Since the result of the function "ignoreArgument" doesn't depend on the
  1402. value of its argument "x", that argument will not be evaluated:
  1403.  
  1404.     ? ignoreArgument (1/0)
  1405.     I didn't need to evaluate x
  1406.     (1 reduction, 31 cells)
  1407.     ?
  1408.  
  1409. In some situations, it is useful to be able to force Gofer to  evaluate
  1410. the argument to a function before the function is applied.  This can be
  1411. achieved using the function "strict" defined in the  standard  prelude;
  1412. An expression of the form "strict f x" is evaluated by first evaluating
  1413. the argument "x" and then applying the function "f" to the result:
  1414.  
  1415.     ? strict ignoreArgument (1/0)
  1416.     {primDivInt 1 0}
  1417.     (4 reductions, 29 cells)
  1418.     ?
  1419.  
  1420. The second  basic  idea  behind  lazy  evaluation  is  that  no  shared
  1421. expression should be  evaluated  more  than  once.   For  example,  the
  1422. following two expressions can be used to calculate 3*3*3*3:
  1423.  
  1424.     ? square * square where square = 3 * 3
  1425.     81
  1426.     (3 reductions, 9 cells)
  1427.     ? (3 * 3) * (3 * 3)
  1428.     81
  1429.     (4 reductions, 11 cells)
  1430.     ?
  1431.  
  1432. Notice that the first expression requires one less reduction  than  the
  1433. second.  Excluding the single reduction step  needed  to  convert  each
  1434. integer into a string, the sequences of reductions that will be used in
  1435. each case are as follows:
  1436.  
  1437. .cc 5
  1438.     square * square where square = 3 * 3
  1439.        -- calculate the value of square by reducing 3 * 3 ==> 9
  1440.        -- and replace each occurrence of square with this result
  1441.        ==> 9 * 9
  1442.        ==> 81
  1443.  
  1444.     (3 * 3) * (3 * 3)   -- evaluate first (3 * 3)
  1445.        ==> 9 * (3 * 3)  -- evaluate second (3 * 3)
  1446.        ==> 9 * 9
  1447.        ==>
  1448.  
  1449. Lazy evaluation is a very powerful feature of programming in a language
  1450. like Gofer, and means that only the minimum amount  of  calculation  is
  1451. used to determine the result of an expression.  The  following  example
  1452. is often used to illustrate this point.
  1453.  
  1454. Consider the task  of  finding  the  smallest  element  of  a  list  of
  1455. integers.  The standard prelude includes a function "minimum" which can
  1456. be used for this very purpose:
  1457.  
  1458.     ? minimum [100,99..1]
  1459.     1
  1460.     (809 reductions, 1322 cells)
  1461.     ?
  1462.  
  1463. (The expression [100,99..1] denotes the list of integers from 1 to  100
  1464. arranged in decreasing order, as described in section 10.1).
  1465.  
  1466. A rather different approach involves sorting the elements of  the  list
  1467. into increasing  order  (using  the  function  "sort"  defined  in  the
  1468. standard prelude) and  then  take  the  element  at  the  head  of  the
  1469. resulting list  (using  the  standard  function  "head").   Of  course,
  1470. sorting the list in its entirety is  likely  to  require  significantly
  1471. more work than the previous approach:
  1472.  
  1473.     ? sort [100,99..1]
  1474.     [1, 2, 3, 4, 5, 6, 7, 8, ... etc ..., 99, 100]
  1475.     (10712 reductions, 21519 cells)
  1476.     ?
  1477.  
  1478. However, thanks to lazy-evaluation, calculating just the first  element
  1479. of the sorted list actually requires less work in this particular  case
  1480. than the first solution using "minimum":
  1481.  
  1482.     ? head (sort [100,99..1])
  1483.     1
  1484.     (713 reductions, 1227 cells)
  1485.     ?
  1486.  
  1487. Incidentally, it is  probably worth  pointing  out  that  this  example
  1488. depends rather heavily on the particular algorithm  used  to  "sort"  a
  1489. list of elements.  The results are rather different if we  compare  the
  1490. same two approaches used to calculate the maximum value in the list:
  1491.  
  1492.     ? maximum [100,99..1]
  1493.     100
  1494.     (812 reductions, 1225 cells)
  1495.     ? last (sort [100,99..1])
  1496.     100
  1497.     (10612 reductions, 20732 cells)
  1498.     ?
  1499.  
  1500. This difference is caused by the fact that each  element  in  the  list
  1501. produced by "sort" is  only  known  once  the  values  of  all  of  the
  1502. preceding elements are also known.  Thus  the  complete  list  must  be
  1503. sorted in order to obtain the last element.
  1504.  
  1505.  
  1506. .ST 9.7  Infinite data structures
  1507. -----------------------------
  1508. One particular benefit of lazy evaluation is that it makes it  possible
  1509. for functions  in  Gofer  to  manipulate  `infinite'  data  structures.
  1510. Obviously we cannot hope either to   construct  or  store  an  infinite
  1511. object in its entirety -- the advantage of lazy evaluation is  that  it
  1512. allows us to construct infinite objects piece  by  piece  as  necessary
  1513. (and to reuse the storage space used by parts of the object  when  they
  1514. are no longer required).
  1515.  
  1516. As a simple example, consider the following function which can be  used
  1517. to produce infinite lists of integer values:
  1518.  
  1519.     countFrom n = n : countFrom (n+1)
  1520.  
  1521. If we evaluate the expression "countFrom 1", Gofer just prints the list
  1522. of integer values beginning with 1 until it is interrupted.  Once  each
  1523. element in the list has been printed, the storage  used  to  hold  that
  1524. element can be reused to hold later elements in the  list.   Evaluating
  1525. this expression is equivalent to using an `infinite' loop to print  the
  1526. list of integers in an imperative programming language:
  1527.  
  1528.     ? countFrom 1
  1529.     [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,^C{Interrupted!}
  1530.     (53 reductions, 160 cells)
  1531.     ?
  1532.  
  1533. For practical applications, we are usually only interested in  using  a
  1534. finite portion of an infinite data  structure  (just  as  loops  in  an
  1535. imperative programming language are usually terminated  after  finitely
  1536. many iterations).  For example, using  "countFrom"  together  with  the
  1537. function "take" defined in the standard  prelude,  we  can  repeat  the
  1538. calculation from section 4 to find the sum of the integers 1 to 10:
  1539.  
  1540.     ? sum (take 10 (countFrom 1))
  1541.     55
  1542.     (62 reductions, 119 cells)
  1543.     ?
  1544.  
  1545. [ASIDE: The expression "take n xs" evaluates to a list  containing  the
  1546. first n elements of the list xs (or to xs itself if the  list  contains
  1547. fewer than n elements).  Thus "countFrom 1" generates the infinite list
  1548. of integers, "take 10" ensures that only the  first  ten  elements  are
  1549. calculated, and "sum" calculates the sum of those integers as before.]
  1550.  
  1551. A particular advantage of using infinite data  structures  is  that  it
  1552. enables us to describe an object without being tied to  one  particular
  1553. application of that object.  Consider the following definition for  the
  1554. infinite list of powers of two [1, 2, 4, 8, ...]:
  1555.  
  1556.     powersOfTwo = 1 : map double powersOfTwo 
  1557.                   where double n = 2*n
  1558.  
  1559. This list be used in a variety of ways; using the operator (!!) defined
  1560. in the standard prelude [xs!!n evaluates to the nth element of the list
  1561. xs], we can define a function to find the nth power of 2 for any  given
  1562. integer n:
  1563.  
  1564.     twoToThe n = powersOfTwo !! n 
  1565.  
  1566. Alternatively, we can use the list "powersOfTwo" to define  a  function
  1567. mapping lists of  bits  (represented  by  integers  0  and  1)  to  the
  1568. corresponding decimal number: simply reverse the order of  the  digits,
  1569. multiply each by the corresponding power of two and calculate the  sum.
  1570. Using functions from the standard  prelude,  this  translates  directly
  1571. into the definition:
  1572.  
  1573.     binToDec ds = sum (zipWith (*) (reverse ds) powersOfTwo)
  1574.  
  1575. For example:
  1576.  
  1577.     ? twoToThe 12
  1578.     4096
  1579.     (15 reductions, 21 cells)
  1580.     ? binToDec [1,0,1,1,0]
  1581.     22
  1582.     (40 reductions, 85 cells)
  1583.     ?
  1584.  
  1585. .ST 9.8  Polymorphism
  1586. -----------------
  1587. Given the definition of "product" in section 9.5, it  is  easy  to  see
  1588. that product takes a single argument which is a list  of  integers  and
  1589. returns a single integer value -- the product of the  elements  of  the
  1590. list.  In other words, "product" has type [Int] -> Int.  On  the  other
  1591. hand, it is not immediately clear what the type of the  function  "map"
  1592. should be.  Clearly the first argument of "map" must be a function  and
  1593. both the second argument and the result are lists, so that the type  of
  1594. "map" must be of the form:
  1595.  
  1596.              (a -> b)   ->      [c]      ->     [d]
  1597.              \______/          \___/           \___/
  1598.            type of 1st      type of 2nd      type of result
  1599.            argument "f"     argument "xs"    "map f xs"
  1600.  
  1601. But what can be said about the types a, b, c and  d?   One  possibility
  1602. would be to choose a = b = c = d = Int which would  be  acceptable  for
  1603. expressions such as  "map  fact  [1,2,3,4]",  but  this  would  not  be
  1604. suitable in an expression such as  "map  chr  [65,75,32]"  because  the
  1605. "chr" function does not have type Int -> Int.
  1606.  
  1607. Notice however that the argument type of "f" must be the  same  as  the
  1608. type of elements in the second argument (i.e.  a  =  c)  since  "f"  is
  1609. applied to each element in that list.  Similarly, the  result  type  of
  1610. "f" must be the same as the type of elements in the result list (i.e. b
  1611. = d) since each element in  this  list  is  obtained  as  a  result  of
  1612. applying the function "f" to some value.  It is therefore reasonable to
  1613. treat the "map" function as having any type of the form:
  1614.  
  1615.                   (a -> b)  ->  [a]  ->  [b]
  1616.  
  1617. The letters  "a"  and  "b"  used  in  this  type  expression  represent
  1618. arbitrary types and are called type variables.  An  object  whose  type
  1619. includes one or more type variables can be thought of  as  having  many
  1620. different types and is often described as having a  `polymorphic  type'
  1621. (literally: its type has `many shapes').
  1622.  
  1623. The ability to define and use polymorphic functions in Gofer turns  out
  1624. to be very useful.  Here are the types of some of the other polymorphic
  1625. functions which have been used in previous  examples  which  illustrate
  1626. this point:
  1627.  
  1628.     length :: [a] -> Int
  1629.     (++)   :: [a] -> [a] -> [a]
  1630.     concat :: [[a]] -> [a]
  1631.  
  1632. Thus we can use precisely the same "length" function to determine  both
  1633. the length of a list of integers as well as finding  the  length  of  a
  1634. string:
  1635.  
  1636.     ? length [1..10]
  1637.     10
  1638.     (98 reductions, 138 cells)
  1639.     ? length "Hello"
  1640.     5
  1641.     (22 reductions, 36 cells)
  1642.     ? 
  1643.  
  1644.  
  1645. .ST 9.9  Higher-order functions
  1646. ---------------------------
  1647. In Gofer, function values are treated in much the same way as any other
  1648. kind of value; in particular, they can be used both  as  arguments  to,
  1649. and results of other functions.
  1650.  
  1651. .cc 5
  1652. Functions which manipulate  other  functions  in  this  way  are  often
  1653. described as `higher-order functions'.  Consider the following example,
  1654. taken from the standard prelude:
  1655.  
  1656.     (.)       :: (b -> c) -> (a -> b) -> (a -> c)
  1657.     (f . g) x  = f (g x)
  1658.  
  1659. As indicated by the type declaration, we think of the (.) operator as a
  1660. function taking two function arguments and returning  another  function
  1661. value as its result.  If f and  g  are  functions  of  the  appropriate
  1662. types, then (f . g) is a function called the composition of f  with  g.
  1663. Applying (f . g) to a value is equivalent to applying g to that  value,
  1664. and then applying f to the result [As described, far  more  eloquently,
  1665. by the second line of the declaration above!].
  1666.  
  1667. Many problems can often be described very elegantly as a composition of
  1668. other functions.  Consider the problem of calculating the total  number
  1669. of characters used in a list of strings.  A simple  recursive  function
  1670. provides one solution:
  1671.  
  1672.     countChars []     = 0
  1673.     countChars (w:ws) = length w + countChars ws 
  1674.  
  1675.     ? countChars ["super","cali","fragi","listic"]
  1676.     20
  1677.     (96 reductions, 152 cells)
  1678.     ?
  1679.  
  1680. An alternative approach is to notice that we can  calculate  the  total
  1681. number of characters by  first  combining  all  of  the  words  in  the
  1682. argument list into a single word (using concat) and  then  finding  the
  1683. length of that word:
  1684.  
  1685.     ? (length . concat) ["super","cali","fragi","listic"]
  1686.     20
  1687.     (113 reductions, 211 cells)
  1688.     ?
  1689.  
  1690. Another solution is to first find the length of each word in  the  list
  1691. (using the "map" function to apply "length"  to  each  word)  and  then
  1692. calculate the sum of these individual lengths:
  1693.  
  1694.     ? (sum . map length) ["super","cali","fragi","listic"]
  1695.     20
  1696.     (105 reductions, 172 cells)
  1697.     ?
  1698.  
  1699.  
  1700. .ST 9.10 Variable declarations
  1701. --------------------------
  1702. A variable declaration  is  a  special  form  of  function  definition,
  1703. almost always consisting of a single equation of the form:
  1704.  
  1705.                            var = rhs
  1706.  
  1707. (i.e. a function declaration of arity 0).  Whereas the  values  defined
  1708. by function declarations of arity>0 are guaranteed to be functions, the
  1709. values defined by variable declarations may or may not be functions:
  1710.  
  1711.     odd = not . even   -- if an integer is not even then it must be odd
  1712.     val = sum [1..100]
  1713.  
  1714. Note that variables defined like this at the top level  of  a  file  of
  1715. definitions will be evaluated using lazy evaluation.  The first time we
  1716. refer  to  the  variable  "val"  defined  above  (either  directly   or
  1717. indirectly), Gofer evaluates the sum of the integers from 1 to 100  and
  1718. overwrites the definition of "val" with this number.  This  calculation
  1719. can then be avoided for each subsequent use of "val" (unless  the  file
  1720. containing the definition of "val" is reloaded).
  1721.  
  1722.     ? val
  1723.     5050
  1724.     (809 reductions, 1120 cells)
  1725.  
  1726.     ? val
  1727.     5050
  1728.     (1 reduction, 7 cells)
  1729.  
  1730.     ?
  1731.  
  1732. Because of this behaviour,  we  should  probably  try  to  avoid  using
  1733. variable declarations where the resulting value will require a  lot  of
  1734. storage space.  If we load a file of definitions including the line:
  1735.  
  1736.     longList = [1..10000]
  1737.  
  1738. and  then  evaluate  the  expression  "length   longList"   (eventually
  1739. obtaining the expected result of 10000), then Gofer will  evaluate  the
  1740. definition of "longList" and replace  it  with  the  complete  list  of
  1741. integers from  1  upto  10000.   Unlike  other  memory  used  during  a
  1742. calculation, it will not be possible to  reuse  this  space  for  other
  1743. calculations without reloading the file defining "longList", or loading
  1744. other files instead.
  1745.  
  1746.  
  1747. .ST 9.11 Pattern bindings and irrefutable patterns
  1748. ----------------------------------------------
  1749. Another useful way of defining variables uses `pattern bindings'  which
  1750. are equations of the form:
  1751.  
  1752.                         pat = rhs
  1753.  
  1754. where the expression on the left hand side is a pattern as described in
  1755. section 9.1.  As a simple example of  pattern  bindings,  here  is  one
  1756. possible definition for the function "head"  which  returns  the  first
  1757. element in a list of values:
  1758.  
  1759.     head xs  =  x  where  (x:ys) = xs
  1760.  
  1761. [The definition  "head (x:_) = x"  used  in  the  standard  prelude  is
  1762. slightly more efficient, but otherwise equivalent.]
  1763.  
  1764. [ASIDE: Note that pattern bindings are treated quite  differently  from
  1765. function bindings (of which the variable declarations described in  the
  1766. last section are a special case).  There are two situations in which an
  1767. ambiguity may occur; i.e. if the left hand side of  an  equation  is  a
  1768. simple variable or an (n+k) pattern of the kind  described  in  section
  1769. 9.1.  In both cases, these are treated as function bindings, the former
  1770. being a variable declaration whilst the latter will  be  treated  as  a
  1771. definition for the operator symbol (+).]
  1772.  
  1773. Pattern bindings are often useful for defining functions which we might
  1774. think of as `returning more  than  one  value'  --  although  they  are
  1775. actually packaged up in a single value such as a tuple.  As an example,
  1776. consider the function "span" defined in the standard prelude.
  1777.  
  1778.     span :: (a -> Bool) -> [a] -> ([a],[a])
  1779.  
  1780. If xs is a list of values and p is a predicate, then span p xs  returns
  1781. the pair of lists (ys,zs) such that ys++zs == xs, all of  the  elements
  1782. in ys satisfy the predicate p and the first  element  of  zs  does  not
  1783. satisfy p.  A suitable definition, using a pattern  binding  to  obtain
  1784. the two lists resulting  from  the  recursive  call  to  "span"  is  as
  1785. follows:
  1786.  
  1787.     span p []               = ([],[])
  1788.     span p xs@(x:xs')
  1789.                 | p x       = let (ys,zs) = span p xs' in (x:ys,zs)
  1790.                 | otherwise = ([],xs)
  1791.  
  1792.  
  1793. For consistency with the lazy evaluation strategy used  in  Gofer,  the
  1794. right hand side of a pattern binding is not evaluated until  the  value
  1795. of one of the  variables  bound  by  that  pattern  is  required.   The
  1796. definition:
  1797.  
  1798.     (0:xs) = [1,2,3]
  1799.  
  1800. will not cause any errors when it is loaded into Gofer, but will  cause
  1801. an error if we attempt to evaluate the variable xs:
  1802.  
  1803.     ? xs
  1804.     {v120 [1, 2, 3]}
  1805.     (11 reductions, 46 cells)
  1806.     ?
  1807.  
  1808. The variable name "v120" appearing in this expression is the name of  a
  1809. function called a `conformality check' which is  defined  automatically
  1810. by Gofer to ensure that the value on the right hand side of the pattern
  1811. binding conforms with the pattern on the left.
  1812.  
  1813. Compare this  with  the  behaviour  of  pattern  matching  in  function
  1814. definitions such as:
  1815.  
  1816.     ? example [1] where example (0:xs) = "Hello"
  1817.     {v126 [1]}
  1818.     (4 reductions, 22 cells)
  1819.     ?
  1820.  
  1821. where  the  equivalent  of  the  conformality  check  is  carried   out
  1822. immediately even if none of the values of the variables in the  pattern
  1823. are actually required.  The reason for  this  difference  is  that  the
  1824. arguments supplied to a function must be evaluated to  determine  which
  1825. equation in the definition of the function should be used.   The  error
  1826. produced by the example above was caused by the fact that the  argument
  1827. [1] does not match the pattern used in the equation defining  "example"
  1828. (represented by an internal Gofer function called "v126").
  1829.  
  1830. A different kind of behaviour can be obtained using a  pattern  of  the
  1831. form ~pat, known as an irrefutable (or lazy) pattern.  This pattern can
  1832. initially be matched against any value, delaying the  check  that  this
  1833. value does indeed match pat until the value of  one  of  the  variables
  1834. appearing in it is required.  The basic idea (together with the  method
  1835. used to implement irrefutable patterns in Gofer) is illustrated by  the
  1836. identity:
  1837.  
  1838.     f ~pat = rhs     is equivalent to     f v = rhs where pat=v
  1839.  
  1840. The following examples, based  very  closely  on  those  given  in  the
  1841. Haskell report [5], illustrate the use of  irrefutable  patterns.   The
  1842. variable "undefined" used in these examples is included in the standard
  1843. prelude  and  causes  a  run-time  error  each  time  it  is  evaluated
  1844. (technically speaking, it represents the bottom element of the relevant
  1845. semantic domain, and is the only value having all possible types):
  1846.  
  1847.    (\ (x,y) -> 0) undefined = {undefined}
  1848.    (\~(x,y) -> 0) undefined = 0
  1849.  
  1850.    (\ [x] -> 0) [] = {v113 []}
  1851.    (\~[x] -> 0) [] = 0
  1852.  
  1853.    (\~[x, (a,b)] -> x) [(0,1),undefined] = {undefined}
  1854.    (\~[x,~(a,b)] -> x) [(0,1),undefined] = (0,1)
  1855.  
  1856.    (\ (x:xs) -> x:x:xs) undefined = {undefined}
  1857.    (\~(x:xs) -> x:x:xs) undefined = {undefined}:{undefined}:{undefined}
  1858.  
  1859. Irrefutable patterns are not used very frequently,  although  they  are
  1860. particularly convenient in some situations (see  section  12  for  some
  1861. examples).  Be careful not to use irrefutable patterns where  they  are
  1862. not appropriate.  An attempt to define a map function "map'" using:
  1863.  
  1864.     map' f ~(x:xs) = f x : map' f xs
  1865.     map' f []      = []
  1866.  
  1867. turns out to be equivalent to the definition:
  1868.  
  1869.     map' f ys  =  f x : map f xs where (x:xs) = ys
  1870.  
  1871. and will not behave as you might have intended:
  1872.  
  1873.     ? map' ord "abc"
  1874.     [97, 98, 99, {v124 []}, {v124 []}, {v^C{Interrupted!}
  1875.     (35 reductions, 159 cells)
  1876.     ?
  1877.  
  1878.  
  1879. .ST 9.12 Type declarations
  1880. -----------------------
  1881. The type system used in Gofer is sufficiently powerful to enable  Gofer
  1882. to determine the type of any function without the need to  declare  the
  1883. types of its arguments and the return  value  as  in  some  programming
  1884. languages.  Despite this, Gofer allows the use of type declarations  of
  1885. the form:
  1886.  
  1887.                 var1, ..., varn :: type
  1888.  
  1889. which enable the programmer  to  declare  the  intended  types  of  the
  1890. variables var1,  ...,  varn  defined  in  either  function  or  pattern
  1891. bindings.   There  are  a  number  of  benefits   of   including   type
  1892. declarations of this kind in a program:
  1893.  
  1894.   o  Documentation: The  type  of  a  function  often  provides  useful
  1895.      information about the way in which a function is  to  be  used  --
  1896.      including the number and order of its arguments.
  1897.  
  1898.   o  Restriction: In some situations, the type of a  function  inferred
  1899.      by Gofer is  more  general  than  is  required.   As  an  example,
  1900.      consider the following function, intended to act as  the  identity
  1901.      on integer values:
  1902.  
  1903.          idInt x  =  x
  1904.  
  1905.      Without an explicit type declaration, Gofer treats  "idInt"  as  a
  1906.      polymorphic function of type a -> a and the expression "idInt 'A'"
  1907.      does not cause a type error.  This problem can be  solved by using
  1908.      an explicit type declaration  to restrict the type of "idInt" to a
  1909.      particular instance of the polymorphic type a -> a:
  1910.  
  1911.          idInt :: Int -> Int
  1912.  
  1913.      Note that a declaration such as:
  1914.  
  1915.          idInt :: Int -> a
  1916.  
  1917.      is not a valid type for the function "idInt"  (the  value  of  the
  1918.      expression "idInt 42" is an  integer  and  cannot  be  treated  as
  1919.      having an arbitrary type, depending  on  the  value  of  the  type
  1920.      variable "a"), and hence will not be accepted by Gofer.
  1921.  
  1922.   o  Consistency check: As illustrated above, declared types are always
  1923.      checked against the definition of a value to make sure  that  they
  1924.      are compatible.   Thus  Gofer  can  be  used  to  check  that  the
  1925.      programmer's intentions (as described by  the  types  assigned  to
  1926.      variables  in  type  declarations)   are   consistent   with   the
  1927.      definitions of those values.
  1928.  
  1929.   o  Overloading: Explicit type declarations can be  used  to  solve  a
  1930.      number  of  problems  associated  with  overloaded  functions  and
  1931.      values.  See section 14 for further details.
  1932. .pa
  1933. .co-------------------------------------------------------------------|
  1934. .>ch10
  1935. .ST 10. INCREASING YOUR POWER OF EXPRESSION
  1936.  
  1937. This section describes a number of useful extensions to the basic range
  1938. of expressions used in the previous sections.  None of  these  add  any
  1939. extra computational power to Gofer -- anything that can  be  done  with
  1940. these constructs  could  also  be  done  with  the  constructs  already
  1941. described.  They are however included in Gofer because they allow  many
  1942. expressions and function definitions to be  written  more  clearly  and
  1943. concisely than the equivalent expressions without these notations.
  1944.  
  1945. .ST 10.1 Arithmetic sequences
  1946. -------------------------
  1947. A number of useful  lists  can  be  generated  using  the  notation  of
  1948. arithmetic  sequences  (so  named  because  of  their   similarity   to
  1949. arithmetic progressions in mathematics).  The following list summarises
  1950. the four forms of sequence  expression  that  can  be  used  in  Gofer,
  1951. together with their translation using the standard functions  enumFrom,
  1952. enumFromTo, enumFromThen and enumFromThenTo:
  1953.  
  1954.     [ n .. ]         enumFrom n
  1955.  
  1956.                      Produces the (potentially infinite) list of values
  1957.                      starting with the value of  n  and  increasing  in
  1958.                      single steps.
  1959.  
  1960.                      e.g. [1..] = [1, 2, 3, 4, 5, 6, 7, 8, 9, etc...
  1961.  
  1962.     [ n .. m ]       enumFromTo n m
  1963.  
  1964.                      Produces the list of  elements  from  n  upto  and
  1965.                      including m in single steps.  If m is less than  n
  1966.                      then the list is empty.
  1967.  
  1968.                      e.g. [-3..3] = [-3, -2, -1, 0, 1, 2, 3]
  1969.                           [1..1]  = [1]
  1970.                           [9..0]  = []
  1971.  
  1972.     [ n, m .. ]      enumFromThen n m
  1973.  
  1974.                      Produces the (potentially infinite) list of values
  1975.                      whose first two elements are given by the values n
  1976.                      and m.  If m is greater than n then the  following
  1977.                      elements of the list are increasing  in  steps  of
  1978.                      the same size.  A similar result is obtained if  m
  1979.                      is less than n  in  which  case  the  elements  of
  1980.                      [n,m..] will be decreasing.  If n and m are  equal
  1981.                      then [n,m..] is an infinite  list  in  which  each
  1982.                      element is equal to n.
  1983.  
  1984.                      e.g. [1,3..] = [1, 3, 5, 7, 9, 11, 13, etc...
  1985.                           [0,0..] = [0, 0, 0, 0, 0, 0, 0, etc...
  1986.                           [5,4..] = [5, 4, 3, 2, 1, 0, -1, etc...
  1987.  
  1988.     [ n, n' .. m ]   enumFromThenTo n n' m
  1989.  
  1990.                      Produces the list of elements from  [n,n'..]  upto
  1991.                      the limit value m.   If  m  is  less  than  n  and
  1992.                      [n,n'..] is increasing, or m is greater than n and
  1993.                      [n,n'..] is decreasing the  resulting list will be
  1994.                      empty.
  1995.  
  1996.                      e.g. [1,3..12] = [1, 3, 5, 7, 9, 11]
  1997.                           [0,0..10] = [0, 0, 0, 0, 0, 0, 0, etc...
  1998.                           [5,4..1]  = [5, 4, 3, 2, 1]
  1999.  
  2000. In  the  standard  prelude,   the   functions   enumFrom,   enumFromTo,
  2001. enumFromThen and enumFromThenTo are overloaded and may also be used  to
  2002. enumerate lists of characters or floating point values:
  2003.  
  2004.     ? ['0'..'9'] ++ ['A'..'Z']
  2005.     0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ
  2006.     (397 reductions, 542 cells)
  2007.  
  2008.     ? [1.2, 1.35 .. 2.00]
  2009.     [1.2, 1.35, 1.5, 1.65, 1.8, 1.95]
  2010.     (56 reductions, 133 cells)
  2011.  
  2012.     ?
  2013.  
  2014. Arithmetic sequences such as those described above play the  same  role
  2015. in functional programming languages as the iterative  `for'  constructs
  2016. in traditional imperative languages.  A good example  of  this  is  the
  2017. example in section 4 used to calculate the sum of the integers  from  1
  2018. upto 10 -- "sum [1..10]".   An  equivalent  program  in  an  imperative
  2019. language might look something like (especially if you think of C!):
  2020.  
  2021.     int i;
  2022.     int total=0;
  2023.     for (i=1; i<=10; i++)
  2024.         total = total + i;
  2025.     return total;
  2026.  
  2027. The advantages of the functional notation in this case are clear:
  2028.  
  2029.    o  It is more compact.
  2030.  
  2031.    o  It separates the task of  generating  the  sequence  of  integers
  2032.       [1..10] from the task of finding their sum.
  2033.  
  2034.    o  It does not require the declaration or use of auxiliary variables
  2035.       such as "i" and "total" in the above.
  2036.  
  2037.  
  2038. .ST 10.2 List comprehensions
  2039. -------------------------
  2040. List comprehensions provide another very powerful and compact  notation
  2041. for describing certain kinds of list expression.  The basic form  of  a
  2042. list comprehension is:
  2043.  
  2044.                       [ <expr> | <qualifiers> ]
  2045.  
  2046. There are three kinds of qualifier that can be used in Gofer:
  2047.  
  2048.   o  Generators: A qualifier of the form pat<-exp is  used  to  extract
  2049.      each element that matches the pattern pat from the list exp in the
  2050.      order that they elements appear in that list.  A simple example of
  2051.      this is the expression [x*x | x<-[1..10]] which denotes  the  list
  2052.      of the squares of the integers between  1  and  10  inclusive  and
  2053.      evaluates to [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] as expected.
  2054.  
  2055.      Formally, we can define the meaning of a list comprehension with a
  2056.      single generator by the equation:
  2057.  
  2058.           [ e | pat <- exp ]  =  loop exp
  2059.                                  where loop []       = []
  2060.                                        loop (pat:xs) = e : loop xs
  2061.                                        loop (_:xs)   = loop xs
  2062.  
  2063.      If pat is an irrefutable pattern (for example,  a  variable)  then
  2064.      this is equivalent to:
  2065.  
  2066.           [ e | pat <- exp ]  =  map f exp
  2067.                                  where f pat = e
  2068.  
  2069.      The full definition is needed for those cases  where  the  pattern
  2070.      pat may not match all of the elements in the list  exp.   This  is
  2071.      the case in expressions such as [ y | (3,y)<-[(1,2),(3,4),(5,6)] ]
  2072.      which evaluates to the singleton list [4].
  2073.  
  2074.   o  Filters: A boolean  valued  expression  may  also  be  used  as  a
  2075.      qualifier in which case it is  often  called  a  filter.   We  can
  2076.      define the meaning of a list comprehension with a single filter by
  2077.      the equation:
  2078.  
  2079.             [ e | condition ]  =  if condition then [e] else []
  2080.  
  2081.      Whilst this form of list comprehension is occasionally  useful  as
  2082.      it stands, it is more common to use filters  in  conjunction  with
  2083.      generators as described below.
  2084.  
  2085.   o  Local definitions: A qualifier of the form pat=expr can be used to
  2086.      introduce a local definition within  a  list  comprehension.   Its
  2087.      meaning can be defined formally using the equation:
  2088.  
  2089.          [ e | pat = exp ]  =  [ let pat=exp in e ]
  2090.  
  2091.      As in the case of filters, local  definitions  are  more  commonly
  2092.      used within lists of more than one qualifier as  described  below.
  2093.      Particular care should be taken to distinguish  a  filter  of  the
  2094.      form pat==expr from a local definition of the form pat=expr.
  2095.  
  2096.      [ASIDE: I originally suggested this form of qualifier in a message
  2097.      sent to the Haskell mailing list, only to discover that a  similar
  2098.      (and more comprehensive) suggestion had been made by Kevin Hammond
  2099.      almost a year earlier.  There was a certain amount of  controversy
  2100.      surrounding the choice of an appropriate syntax and semantics  for
  2101.      the construct and consequently, this feature is not currently part
  2102.      of the Haskell  standard.   The  syntax  and  semantics  above  is
  2103.      implemented by Gofer in the hope  that  it  will  give  functional
  2104.      programmers an opportunity to experiment  with  this  facility  in
  2105.      their own programs.]
  2106.  
  2107. The real power of this notation is that it is possible to  use  several
  2108. qualifiers, separated by commas on the right of the  vertical  bar  `|'
  2109. symbol in a list comprehension.  Formally, if qs1 and qs2 are two  such
  2110. lists of qualifiers,  then  we  can  define  the  meaning  of  multiple
  2111. qualifiers using:
  2112.  
  2113.          [ e | qs1, qs2 ]  =  concat [ [ e | qs2 ] | qs1 ]
  2114.  
  2115. The  following  examples  illustrate  how  this  definition  works   in
  2116. practice:
  2117.  
  2118.   o  Variables generated by later qualifiers  vary  more  quickly  than
  2119.      those generated by earlier qualifiers:
  2120.  
  2121.          ? [ (x,y) | x<-[1..3], y<-[1..2] ]
  2122.          [(1,1), (1,2), (2,1), (2,2), (3,1), (3,2)]
  2123.          (107 reductions, 246 cells)
  2124.          ?
  2125.  
  2126.   o  Later qualifiers may use the values generated by earlier ones:
  2127.  
  2128.          ? [ (x,y) | x<-[1..3], y<-[1..x]]
  2129.          [(1,1), (2,1), (2,2), (3,1), (3,2), (3,3)]
  2130.          (107 reductions, 246 cells)
  2131.  
  2132.          ? [ x | x<-[1..10], even x ]
  2133.          [2, 4, 6, 8, 10]
  2134.          (108 reductions, 171 cells)
  2135.          ?
  2136.  
  2137.   o  Variables defined in later qualifiers  hide  those  introduced  by
  2138.      earlier  ones.   The  following   expressions   are   valid   list
  2139.      comprehensions, but this style of definition in  which  names  are
  2140.      reused can result in programs which are difficult  to  understand,
  2141.      and is not recommended:
  2142.  
  2143.          ? [ x | x<-[[1,2],[3,4]], x<-x ]
  2144.          [1, 2, 3, 4]
  2145.          (18 reductions, 53 cells)
  2146.  
  2147.          ? [ x | x<-[1,2], x<-[3,4] ]
  2148.          [3, 4, 3, 4]
  2149.          (18 reductions, 53 cells)
  2150.          ?
  2151.  
  2152.   o  Changing  the  order  of  qualifiers  has  a  direct   effect   on
  2153.      efficiency.  The following two examples produce the  same  result,
  2154.      but the first uses more reductions and cells  because  it  repeats
  2155.      the evaluation of "even x" for each possible value of "y".
  2156.  
  2157.          ? [ (x,y) | x<-[1..3], y<-[1..2], even x ]
  2158.          [(2,1), (2,2)]
  2159.          (110 reductions, 186 cells)
  2160.  
  2161.          ? [ (x,y) | x<-[1..3], even x, y<-[1..2] ]
  2162.          [(2,1), (2,2)]
  2163.          (62 reductions, 118 cells)
  2164.          ? 
  2165.  
  2166.      The following example illustrates a similar kind of behaviour with
  2167.      local definitions; in the first case the expression  "fact  x"  is
  2168.      evaluated twice for each possible value of "x", whilst the  second
  2169.      expression uses a local definition to ensure that  the  evaluation
  2170.      is not repeated:
  2171.  
  2172.          ? [ fact x + y | x<-[1..3], y<-[1..2] ]
  2173.          [2, 3, 3, 4, 7, 8]
  2174.          (246 reductions, 398 cells)
  2175.  
  2176.          ? [ factx + y | x<-[1..3], factx = fact x, y<-[1..2] ]
  2177.          [2, 3, 3, 4, 7, 8]
  2178.          (173 reductions, 294 cells)
  2179.          ?
  2180.  
  2181.  
  2182. .ST 10.3 Lambda expressions
  2183. ------------------------
  2184. In addition to  named  function  definitions,  Gofer  also  allows  the
  2185. definition and use of unnamed functions using a `lambda expression'  of
  2186. the form:
  2187.  
  2188.                   \ <atomic patterns> -> <expr>
  2189.  
  2190. [ASIDE:  This  is  a  slight  generalisation  of  the  form  of  lambda
  2191. expression  used  in  most   theoretical   treatments   of   functional
  2192. programming and  dating  back  to  the  pioneering  work  of  logicians
  2193. including  Alonzo Church and  Haskell Curry,  from whom the programming
  2194. language takes its name.  The `\' character used at the beginning of  a
  2195. Gofer lambda expression has been  chosen  for  its  resemblance  to the
  2196. greek letter lambda that might be used if the  standard  character  set
  2197. were  a little larger.]
  2198.  
  2199. This expression denotes a function taking a number of  parameters  (one
  2200. for each pattern) and producing the result specified by the  expression
  2201. to the right of the -> symbol.  For example, (\x->x*x)  represents  the
  2202. function which takes a single integer argument  `x'  and  produces  the
  2203. square of that  number as its result.   Another  example is the  lambda
  2204. expression (\x y->x+y) which takes two integer  arguments  and  outputs
  2205. their sum; this expression is in fact equivalent to the (+) operator:
  2206.  
  2207.     ? (\x y->x+y) 2 3
  2208.     5
  2209.     (3 reductions, 7 cells)
  2210.     ?
  2211.  
  2212. A lambda expression of the form illustrated above is equivalent to  the
  2213. following expression using a local definition:
  2214.  
  2215.       (let newName <atomic patterns> = <expr> in newName)
  2216.  
  2217. where "newName" is a new variable name, chosen to avoid conflicts  with
  2218. other variables that are already in use.  This name will be printed  if
  2219. you enter an expression involving a lambda expression without supplying
  2220. the full number of parameters for that function:
  2221.  
  2222.     ? (\x y -> x+y) 42
  2223.     v117 42
  2224.     (2 reductions, 14 cells)
  2225.     ?
  2226.  
  2227. Lambda expressions  are  particularly  useful  for  certain  styles  of
  2228. functional programming; an example of this  is  the  continuation-based
  2229. approach to I/O described in section 12.
  2230.  
  2231.  
  2232. .ST 10.4 Case expressions
  2233. ---------------------
  2234. A case expression can be used to evaluate an expression and,  depending
  2235. on the result, return one of a number of  possible  values.   As  such,
  2236. case statements are a  straightforward  generalisation  of  conditional
  2237. expressions.  Indeed, an expression of the form "if e then t else f" is
  2238. in fact equivalent to the case expression:
  2239.  
  2240.                         case e of 
  2241.                           True  -> t
  2242.                           False -> f
  2243.  
  2244. In general, a case expression takes the form "case exp of  alts"  where
  2245. exp  is  the  expression  to  be  evaluated  and  alts  is  a  list  of
  2246. alternatives, each of which is of the form:
  2247.  
  2248.         pat -> rhs                    for a simple alternative
  2249.  
  2250.     or: pat | condition1 -> rhs1      using guard expressions as
  2251.             | condition2 -> rhs2      described in section 9.2 for
  2252.                   .                   function definitions
  2253.                   .
  2254.             | conditionn -> rhsn
  2255.  
  2256. In Gofer, a case expression of the form case e of alts  is  implemented
  2257. by choosing a new function name "newName" as in  the  previous  section
  2258. and  using  the  alternatives  in  alts  to  construct  an  appropriate
  2259. definition for this function (essentially by replacing each `->' symbol
  2260. with a `=' symbol).  The complete case expression is  then  treated  as
  2261. being equivalent to the expression "newName e".  A  simple  example  of
  2262. this is the "scanl" function whose definition in the standard prelude:
  2263.  
  2264.     scanl f q xs = q : (case xs of
  2265.                         []   -> []
  2266.                         x:xs -> scanl f (f q x) xs)
  2267.  
  2268. is equivalent to:
  2269.  
  2270.     scanl f q xs = q : scanl' xs
  2271.                    where scanl' []     = []
  2272.                          scanl' (x:xs) = scanl f (f q x) xs
  2273.  
  2274. This latter form is precisely the definition used in [1] (but using the
  2275. name "scan" where Gofer uses "scanl").
  2276.  
  2277. Evaluating a case expression in which none of  the  alternatives  match
  2278. the value  of  the  discriminant  results  in  an  error  such  as  the
  2279. following:
  2280.  
  2281.     ? case [1,2] of [] -> "empty list"
  2282.     {v117 [1, 2]}
  2283.     (6 reductions, 31 cells)
  2284.     ?
  2285.  
  2286. The function name "v117" which appears here is the name of the function
  2287. which is used internally by Gofer  to  implement  the  case  expression
  2288. whilst the expression "[1, 2]" gives the discriminant value which could
  2289. not be matched.
  2290.  
  2291. By combining case expressions with the lambda expressions introduced in
  2292. the previous section, any function declaration can be translated into a
  2293. single equation of the form <functionName> = <expr>.  For example,  the
  2294. standard function "map" whose definition is usually written as:
  2295.  
  2296.     map f []     = []
  2297.     map f (x:xs) = f x : map f xs
  2298.  
  2299. can also be defined by the equation:
  2300.  
  2301.     map = \f xs -> case xs of
  2302.                      []     -> []
  2303.                      (y:ys) -> f y : map f ys
  2304.  
  2305. This kind  of  translation  is  used  in  the  implementation  of  many
  2306. functional programming languages, including Gofer.   See  Simon  Peyton
  2307. Jones book [2] for more details of this.
  2308.  
  2309.  
  2310. .ST 10.5 Operator sections
  2311. ----------------------
  2312. As we have seen, most functions in Gofer taking more than one  argument
  2313. are treated as a function of a  single  argument,  whose  result  is  a
  2314. function which can then be applied to the  remaining  arguments.   Thus
  2315. "(+) 1" denotes the function which takes an integer  argument  "n"  and
  2316. returns the integer value "1+n".   Functions  of  this  kind  involving
  2317. operator symbols are sufficiently common that Gofer provides a  special
  2318. syntax for them.  Using e to denote an atomic expression and the symbol
  2319. "*" to represent an arbitrary infix operator, there are functions (e *)
  2320. and (* e), known as `sections of the operator (*)' defined by:
  2321.  
  2322.                   (e *) x  = e * x
  2323.                   (* e) x  = x * e
  2324.  
  2325. or, using lambda expressions as introduced in section 10.3:
  2326.  
  2327.                   (e *)    =  \x -> e * x
  2328.                   (* e)    =  \x -> x * e
  2329.  
  2330. For example: (1+)   is the successor function which returns the value
  2331.                     of its argument plus 1,
  2332.              (1.0/) is the reciprocal function,
  2333.              (/2)   is the halving function,
  2334.              (:[])  is the function which maps any value to the
  2335.                     singleton list containing that element.
  2336.  
  2337. In Gofer, the expressions "(e *)" and "(* e)" are actually  treated  as
  2338. abbreviations for "(*) e" and "flip (*) e" respectively,  where  "flip"
  2339. is the function defined by:
  2340.  
  2341.      flip        :: (a -> b -> c) -> b -> a -> c
  2342.      flip  f x y  =  f y x
  2343.  
  2344. There is an important special case which occurs with an  expression  of
  2345. the form (- e); this is interpreted  as  "negate  e"  and  not  as  the
  2346. section which subtracts the value of "e" from its argument.  The latter
  2347. function can be written as the section (+ (- e))  or  as  "subtract  e"
  2348. where "subtract" is the function defined in the standard prelude using:
  2349.  
  2350.     subtract = flip (-)
  2351.  
  2352.  
  2353. .ST 10.6 Explicitly typed expressions
  2354. ----------------------------------
  2355. As described in section 9.12, it is often useful to be able to  declare
  2356. the type of a variable defined in a function or pattern  binding.   For
  2357. much the same reasons, Gofer allows expressions of the form:
  2358.  
  2359.                          <expr> :: <type>
  2360.  
  2361. so that the type of an expression can be  specified  explicitly.   Note
  2362. that the :t command can be used  to  find  the  type  of  a  particular
  2363. expression that is inferred by Gofer:
  2364.  
  2365.     ? :t  \x -> [x]
  2366.     \x -> [x] :: a -> [a]
  2367.  
  2368.     ? :t  sum . map length
  2369.     sum . map length :: [[a]] -> Int
  2370.  
  2371.     ? 
  2372.  
  2373. The types inferred in each case can be modified by  including  explicit
  2374. types in these expressions:
  2375.  
  2376.     ? :t  (\x -> [x]) :: Char -> String
  2377.     \x -> [x] :: Char -> String
  2378.  
  2379.     ? :t  sum . map (length :: String -> Int)
  2380.     sum . map length :: [String] -> Int
  2381.  
  2382.     ?
  2383.  
  2384. Note that an error occurs if the type declared in an  explicitly  typed
  2385. expression is not compatible with the type inferred by Gofer:
  2386.  
  2387.     ? :t (\x -> [x]) :: Int -> a
  2388.     ERROR: Declared type too general
  2389.     *** Expression    : \x -> [x]
  2390.     *** Declared type : Int -> a
  2391.     *** Inferred type : Int -> [Int]
  2392.  
  2393.     ?
  2394.  
  2395. Explicitly typed expressions  are  most  commonly  used  together  with
  2396. overloaded functions and values as described in section 14.
  2397. .pa
  2398. .co-------------------------------------------------------------------|
  2399. .>ch11
  2400. .ST 11. USER-DEFINED DATATYPES AND TYPE SYNONYMS
  2401.  
  2402. .ST 11.1 Datatype definitions
  2403. -------------------------
  2404. In addition to the  wide  range  of  built-in  datatypes  described  in
  2405. section 7, Gofer also allows the  definition  of  new  datatypes  using
  2406. declarations of the form:
  2407.  
  2408.      data DatatypeName a1 ... an = constr1 | ... | constrm
  2409.  
  2410. where DatatypeName is the name of a new type constructor of arity n>=0,
  2411. a1, ..., an are distinct type variables representing the  arguments  of
  2412. DatatypeName and constr1, ..., constrm (m>=1) describe the way in which
  2413. elements of the new datatype are constructed.  Each constr can take one
  2414. of two forms:
  2415.  
  2416.   o  Name type1 ... typer where Name is a previously unused constructor
  2417.      function  name  (i.e.  an  identifier  beginning  with  a  capital
  2418.      letter).  This declaration introduces Name as  a  new  constructor
  2419.      function of type: type1 -> ...-> typer -> DatatypeName a1 ... an.
  2420.  
  2421.   o  type1 CONOP type2 where CONOP is a previously  unused  constructor
  2422.      function  operator (i.e.  an  operator  symbol  beginning  with  a
  2423.      colon).  This declaration introduces (CONOP) as a new  constructor
  2424.      function of type: type1 -> type2 -> DatatypeName a1 ... an.
  2425.  
  2426. [N.B. only the  type variables  a1, ..., an  may  appear  in  the  type
  2427. expressions in each constr in the definition of DatatypeName.]
  2428.  
  2429.  
  2430. As a simple example, the following definition introduces a new type Day
  2431. with elements Sun, Mon, Tue, Wed, Thu, Fri and Sat:
  2432.  
  2433.     data Day = Sun | Mon | Tue | Wed | Thu | Fri | Sat
  2434.  
  2435. Simple functions manipulating elements of type Day can be defined using
  2436. pattern matching:
  2437.  
  2438.     what_shall_I_do Sun = "relax"
  2439.     what_shall_I_do Sat = "go shopping"
  2440.     what_shall_I_do _   = "looks like I'll have to go to work"
  2441.  
  2442. Another example uses a pair of constructors to provide a representation
  2443. for temperatures which may be given using either of the  centigrade  or
  2444. fahrenheit scales:
  2445.  
  2446.     data Temp = Centigrade Float | Fahrenheit Float
  2447.  
  2448.     freezing                  :: Temp -> Bool
  2449.     freezing (Centigrade temp) = temp <= 0.0
  2450.     freezing (Fahrenheit temp) = temp <= 32.0
  2451.  
  2452. The following example uses a type variable on the left hand side of the
  2453. datatype  definition  to  implement  a   Set   type   constructor   for
  2454. representing sets using a list of values:
  2455.  
  2456.     data Set a = Set [a]
  2457.  
  2458. For example, Set [1,2,3] is an element of type  Set  Int,  representing
  2459. the set of integers {1, 2, 3} whilst Set ['a'] represents  a  singleton
  2460. set of type Set Char.  As this example shows, it is possible to use the
  2461. same  name  simultaneously  as  both  a  type  constructor  and  as   a
  2462. constructor function.
  2463.  
  2464. Datatype definitions may also be  recursive,  using  the  name  of  the
  2465. datatype  being  defined  on  the  right  hand  side  of  the  datatype
  2466. definition  (mutually   recursive   datatype   definitions   are   also
  2467. permitted).  The following example is taken from the Haskell report [5]
  2468. and  defines  a  type  representing  binary  trees  with  values  of  a
  2469. particular type at their leaves:
  2470.  
  2471.     data Tree a = Lf a | Tree a :^: Tree a
  2472.  
  2473. For example, (Lf 12 :^: (Lf 23 :^: Lf 13)) :^: Lf 10 has type Tree  Int
  2474. and represents the binary tree:
  2475.  
  2476.                               ,--- 12
  2477.                            ,--| 
  2478.                            |  |  ,--- 23
  2479.                            |  `--| 
  2480.                            |     `--- 13
  2481.                          --| 
  2482.                            `--- 10
  2483.  
  2484. As an example of a function defined on trees, here are two  definitions
  2485. using recursion and pattern matching on tree valued  expressions  which
  2486. calculate the list of elements at the leaves of a tree  traversing  the
  2487. branches of the tree from left to right.  The first definition  uses  a
  2488. simple definition, whilst the second uses an  `accumulating  parameter'
  2489. giving a more efficient algorithm:
  2490.  
  2491.     leaves, leaves'  :: Tree a -> [a]
  2492.  
  2493.     leaves (Lf l)  = [l]
  2494.     leaves (l:^:r) = leaves l ++ leaves r
  2495.  
  2496.     leaves' t = leavesAcc t []
  2497.                  where leavesAcc (Lf l)  = (l:)
  2498.                        leavesAcc (l:^:r) = leavesAcc l . leavesAcc r
  2499.  
  2500. Using the binary tree above as an example:
  2501.  
  2502.     ? leaves ((Lf 12 :^: (Lf 23 :^: Lf 13)) :^: Lf 10)
  2503.     [12, 23, 13, 10]
  2504.     (24 reductions, 73 cells)
  2505.     ? leaves' ((Lf 12 :^: (Lf 23 :^: Lf 13)) :^: Lf 10)
  2506.     [12, 23, 13, 10]
  2507.     (20 reductions, 58 cells)
  2508.     ?
  2509.  
  2510.  
  2511. .ST 11.2 Type synonyms
  2512. ------------------
  2513. Type synonyms are used to provide  convenient  abbreviations  for  type
  2514. expressions.  A type synonym is introduced  by  a  declaration  of  the
  2515. form:
  2516.  
  2517.      type Name a1 ... an = expansion
  2518.  
  2519. where Name is the name of a new type constructor  of  arity  n>=0,  a1,
  2520. ..., an are distinct type variables representing the arguments of  Name
  2521. and expansion is a type expression.  Note that the only type  variables
  2522. permitted in the expansion type are those on the left hand side of  the
  2523. synonym definition.  Using this declaration any type expression of  the
  2524. form:
  2525.  
  2526.                   Name type1 ... typen 
  2527.  
  2528. is treated as an abbreviation of  the  type  expression  obtained  from
  2529. expansion by replacing each of the type variables a1, ..., an with  the
  2530. corresponding type type1, ..., typen.
  2531.  
  2532. The most frequently used type synonym is almost  certainly  the  String
  2533. type which is a synonym for [Char]:
  2534.  
  2535.     type String = [Char]
  2536.  
  2537. [ASIDE: This definition is actually built in to the Gofer  system,  but
  2538. the effect is the same as if this  declaration  were  included  in  the
  2539. standard prelude.]
  2540.  
  2541. Note that the types of expressions inferred by Gofer will  not  usually
  2542. contain any type synonyms unless an explicit type signature  is  given,
  2543. either using an explicitly typed expression (section 10.6)  or  a  type
  2544. declaration (section 9.12):
  2545.  
  2546.     ? :t ['c']
  2547.     ['c'] :: [Char]
  2548.     ? :t ['c'] :: String
  2549.     ['c'] :: String
  2550.     ?
  2551.  
  2552. Unlike the datatype declarations described  in  the  previous  section,
  2553. recursive  (and  mutually  recursive)  synonym  declarations  are   not
  2554. permitted.  This rules out examples such as:
  2555.  
  2556.     type BadSynonym = [BadSynonym]
  2557.  
  2558. and ensures that the process of expanding all of the type synonyms used
  2559. in any particular type expression  will  always  terminate.   The  same
  2560. property does not hold for the illegal definition above, in  which  any
  2561. attempt to expand the type BadSynonym would lead to the non-terminating
  2562. sequence:
  2563.  
  2564.     BadSynonym ==> [BadSynonym] ==> [[BadSynonym]] ==> ....
  2565. .pa
  2566. .co-------------------------------------------------------------------|
  2567. .>ch12
  2568. .ST 12. DIALOGUES: INPUT AND OUTPUT
  2569.  
  2570. The Gofer system implements a subset of  the  facilities  for  programs
  2571. involving I/O described in the Haskell report [5].  In particular, this
  2572. makes it possible for Gofer programs to be run  interactively,  and  to
  2573. make limited use of  text  files  for  both  reading  and  writing.   A
  2574. significant factor in the design of the Haskell I/O facilities is  that
  2575. it allows  the  use  of  such  programs  without  loss  of  referential
  2576. transparency.
  2577.  
  2578. .ST 12.1 Basic description
  2579. ----------------------
  2580. Programs using the I/O facilities in Gofer are modelled by functions of
  2581. type Dialogue, defined by the type synonym:
  2582.  
  2583.     type Dialogue    =  [Response] -> [Request]
  2584.  
  2585. In other words, a Gofer program produces a list of output values,  each
  2586. of which may be thought of as a request for some  particular  input  or
  2587. output action, and obtains the corresponding list of  operating  system
  2588. responses as its input.  Note that the input list of responses will  be
  2589. evaluated lazily; i.e. we can ensure that we do not attempt  to  obtain
  2590. the response to a given request until that request has been completed.
  2591.  
  2592. The current range of requests supported by Gofer is  described  by  the
  2593. following datatype definition, taken from the standard prelude:
  2594.  
  2595.     data Request  =  -- file system requests:
  2596.                     ReadFile      String         
  2597.                   | WriteFile     String String
  2598.                   | AppendFile    String String
  2599.                      -- channel system requests:
  2600.                   | ReadChan      String 
  2601.                   | AppendChan    String String
  2602.                      -- environment requests:
  2603.                   | Echo          Bool
  2604.  
  2605. Each response is an element  of  the  type  defined  by  the  following
  2606. datatype definition, using an auxiliary datatype IOError to describe  a
  2607. variety of error conditions that may occur:
  2608.  
  2609.     data Response = Success
  2610.                   | Str String 
  2611.                   | Failure IOError
  2612.  
  2613.     data IOError  = WriteError   String
  2614.                   | ReadError    String
  2615.                   | SearchError  String
  2616.                   | FormatError  String
  2617.                   | OtherError   String
  2618.  
  2619. The following list describes the kind of  I/O  behaviour  specified  by
  2620. each form of Request and indicates the possible  Response  values  that
  2621. may be obtained in each case:
  2622.  
  2623.   o  ReadFile  string:  Read  contents  of  file  named  by   "string".
  2624.      Possible responses to this request are:
  2625.  
  2626.        o  Str contents  if the request is successful,  where "contents"
  2627.           is a string (evaluated lazily) containing the contents of the
  2628.           file specified by the ReadFile request.
  2629.  
  2630.        o  Failure (SearchError name) occurs if file  "name"  cannot  be
  2631.           accessed.
  2632.  
  2633.        o  Failure (ReadError name) occurs if some  other  error  occurs
  2634.           whilst opening the file "name".
  2635.  
  2636.   o  WriteFile name string:  Write  the  given  "string"  to  the  file
  2637.      "name".  If the file does not already exist, it is created  before
  2638.      attempting to write the value to file.  If the file already exists
  2639.      then it will be truncated to zero length before the write  begins.
  2640.      No response is obtained until the string argument has  been  fully
  2641.      evaluated and its contents written to  file.   Possible  responses
  2642.      are:
  2643.  
  2644.        o  Success if the write to file was completed successfully.
  2645.  
  2646.        o  Failure (WriteError msg) if  an  error  was  detected  whilst
  2647.           trying to perform the output.  If the problem occurred whilst
  2648.           attempting to open the specified file,  then  "msg"  contains
  2649.           the   filename,   otherwise   it   contains    a    printable
  2650.           representation of the evaluation error which occurred.
  2651.  
  2652.   o  AppendFile name string: Similar to the  WriteFile  request  except
  2653.      that the value of the given "string" is  appended  onto  the  file
  2654.      "name" if that file already exists.  The  responses  that  may  be
  2655.      obtained from this request are the same as those for WriteFile.
  2656.  
  2657.   o  ReadChan name:  Read  from  the  input  stream  "name".  Note that
  2658.      it is an error to attempt to read from the same channel more  than
  2659.      once in the same program.  Possible responses are:
  2660.  
  2661.        o  Str contents if the request is successful,  where  "contents"
  2662.           is  a  string  (evaluated  lazily)  containing  the  list  of
  2663.           characters entered on the input stream.
  2664.  
  2665.        o  Failure (SearchError name) if the  named  channel  cannot  be
  2666.           found.  The only input channel known to Gofer is the standard
  2667.           input channel "stdin".  For convenience, the standard prelude
  2668.           defines the variable stdin bound to this string.
  2669.  
  2670.        o  Failure (ReadError name) if a ReadChan request for the  named
  2671.           channel has already been given by a previous request.
  2672.  
  2673.   o  AppendChan name string:  Output "string" on  channel  "name".   No
  2674.      response is obtained until the string has been fully evaluated and
  2675.      written to the named channel.  Possible responses are:
  2676.  
  2677.        o  Success if the append to channel was completed successfully.
  2678.  
  2679.        o  Failure (SearchError name) if the  named  channel  cannot  be
  2680.           found.  The only output channels known to Gofer are "stdout",
  2681.           "stderr" and "stdecho" (which is actually just  another  name
  2682.           for  "stdout"  in  Gofer).   For  convenience,  the  standard
  2683.           prelude defines variables stdout, stderr and stdecho bound to
  2684.           the corresponding string values.
  2685.  
  2686.        o  Failure (WriteError msg)  if  an  error  is  detected  whilst
  2687.           trying to perform the output.  The string  "msg"  contains  a
  2688.           printable  representation  of  the  evaluation  error   which
  2689.           occurred.
  2690.  
  2691.   o  Echo status: Set the echo status on  the  standard  input  channel
  2692.      stdin to the given boolean value.  If the  echo  status  is  True,
  2693.      then user input will be echoed onto the screen as it is  typed and
  2694.      the usual line editing facilities  (such a  backspace  or  delete)
  2695.      provided by the host system can be used to edit the input lines as
  2696.      they are entered.  If the echo status is  False,  then  individual
  2697.      characters may be read from the standard input channel without any
  2698.      echo or line editing features.
  2699.  
  2700.      Note that at most one Echo request can be used in a  program,  and
  2701.      must precede any ReadChan request for stdin.  If  not  set  by  an
  2702.      explicit Echo request, the echo status defaults to True.  Possible
  2703.      responses are:
  2704.  
  2705.        o  Success if the request was completed successfully.
  2706.  
  2707.        o  Failure  (OtherError  msg)  if  the  request  could  not   be
  2708.           completed either because a readChannel request for stdin  has
  2709.           already been processed, or because a  previous  Echo  request
  2710.           has already been given.  The  corresponding  values of  "msg"
  2711.           are   "stdin already in use"   and    "repeated Echo request"
  2712.           respectively.
  2713.  
  2714. A simple example of a program using these facilities to output a short
  2715. message on the standard output stream is:
  2716.  
  2717.     helloWorld      :: Dialogue
  2718.     helloWorld resps = [AppendChan stdout "hello, world"]
  2719.  
  2720. Any expression entered into Gofer of type "Dialogue" will be treated as
  2721. a Gofer program using I/O and will be executed accordingly:
  2722.  
  2723.     ? helloWorld
  2724.     hello, world
  2725.     (1 reduction, 28 cells)
  2726.     ?
  2727.  
  2728. Notice that without the explicit type declaration, the type that  would
  2729. be  inferred  for  helloWorld   would   be  a -> [Request],  and  hence
  2730. helloWorld would not be executed as a Dialogue program.  This point can
  2731. be illustrated using lambda expressions:
  2732.  
  2733.     ? \resps -> [AppendChan stdout "hello, world"]
  2734.     v128
  2735.     (1 reduction, 7 cells)
  2736.  
  2737.     ? (\resps -> [AppendChan stdout "hello, world"]) :: Dialogue
  2738.     hello, world
  2739.  
  2740.     (1 reduction, 28 cells)
  2741.     ? 
  2742.  
  2743. In many cases the  structure  of  an  expression  is  enough  to  fully
  2744. determine its type  as  Dialogue  (or  equivalently  as  [Response]  ->
  2745. [Request]), in which case no explicit types are required to ensure that
  2746. the expression is treated as a Gofer program using I/O:
  2747.  
  2748.     ? \~[Success] -> [AppendChan stdout "hello, world"]
  2749.     hello, world
  2750.     (1 reduction, 29 cells)
  2751.     ?
  2752.  
  2753. Note the use of the  irrefutable  pattern  ~[Success]  for  the  lambda
  2754. expression in the last  example;  without  this,  the  usual  rules  of
  2755. pattern matching as described in section 9 would force Gofer to try  to
  2756. match the pattern [Success] against the list of responses,  before  the
  2757. corresponding request had been produced:
  2758.  
  2759.     ? \ [Success] -> [AppendChan stdout "hello, world"]
  2760.  
  2761.     Aborting Dialogue:
  2762.           {error "Attempt to read response before request complete"}
  2763.     (50 reductions, 229 cells)
  2764.     ?
  2765.  
  2766. The next example takes a single string as a parameter and displays  the
  2767. contents of the corresponding file:
  2768.  
  2769.     showFile               :: String -> Dialogue 
  2770.     showFile name ~(read:_) = [ReadFile name, AppendChan stdout result] 
  2771.      where result = case read of Str contents -> contents 
  2772.                                  Failure _    -> "Can't open " ++ name 
  2773.  
  2774. With a few modifications, we can  implement  a  similar  program  which
  2775. prompts for, and reads, a filename from the  standard  input  and  then
  2776. reads and displays the contents of that file as before.   This  program
  2777. is based on a similar example in the Haskell report [5]:
  2778.  
  2779.     main ~(Success : ~(Str userInput : ~(r3 : _)))  
  2780.       = [ AppendChan stdout "Please type a filename: ", 
  2781.           ReadChan stdin, 
  2782.           ReadFile name, 
  2783.           AppendChan stdout (case r3 of Str contents -> contents
  2784.                                         Failure _    -> "Can't open "
  2785.                                                         ++ name)
  2786.         ] where (name : _) = lines userInput
  2787.  
  2788.  
  2789. .ST 12.2 Continuation style I/O
  2790. ---------------------------
  2791. As an alternative to the `stream-based' approach to programs using  the
  2792. I/O facilities in Gofer, the  standard  prelude  defines  a  family  of
  2793. functions which enables such programs to be written in a `continuation'
  2794. style.  The basic idea is to define a function  corresponding  to  each
  2795. different kind of request, whose parameters include the values required
  2796. to make the request together with two continuations.  The continuations
  2797. are functions describing "what to do next", one of which is used if the
  2798. request is successful, the other if the request fails.
  2799.  
  2800. As an example, the ReadFile request  is  represented  by  the  function
  2801. "readFile" whose definition is equivalent to:
  2802.  
  2803.     readFile name fail succ ~(r:rs) = ReadFile name : rest rs
  2804.      where rest = case r of Str s           -> succ s
  2805.                             Failure ioerror -> fail ioerror
  2806.  
  2807. The first thing to happen  when  a  dialogue  expression  of  the  form
  2808. "readFile name fail  succ"  is  evaluated  is  that  the  corresponding
  2809. request "ReadFile name" is added to the list of I/O  requests.   A  new
  2810. dialogue value "rest" is chosen,  depending  on  the  response  to  the
  2811. ReadFile request, and the program continues by  passing  the  remaining
  2812. part of the response list to "rest".  The functions "succ"  and  "fail"
  2813. (called the success and failure  continuations  respectively)  describe
  2814. the way in which the new dialogue "rest" is obtained.
  2815.  
  2816. The following example (edited a little to fit within the margins of this
  2817. document) shows how the readFile function described above can be used to
  2818. print the contents of a file called "test" on the display:
  2819.  
  2820.     ? readFile "test" (\ioerror resps -> [])
  2821.                       (\s resps->[AppendChan stdout s])
  2822.     This is a test message
  2823.  
  2824.     (4 reductions, 52 cells)
  2825.     ?
  2826.  
  2827. The success continuation "(\s resps->[AppendChan stdout s])" used  here
  2828. receives the contents of the file "test" in the the parameter  "s"  and
  2829. uses an AppendChan request to output that string on  the  display.   As
  2830. this example shows, the stream based approach of the  previous  section
  2831. can be combined with the continuation based style of  I/O  without  any
  2832. difficulty.  The failure continuation "(\ioerror resps -> [])"  ignores
  2833. the error condition "ioerror" which caused  the  request  to  fail  and
  2834. gives a dialogue which terminates immediately without any action.   For
  2835. example, assuming that the file "Test" cannot be found:
  2836.  
  2837.     ? readFile "Test" (\ioerror resps -> [])
  2838.                       (\s resps->[AppendChan stdout s])
  2839.  
  2840.     (4 reductions, 24 cells)
  2841.     ?
  2842.  
  2843. In practice, it is  usually  a  good  idea  to  produce  some  kind  of
  2844. diagnostic message when an error occurs:
  2845.  
  2846.     ? readFile "Test"
  2847.          (\ioerror resps -> [AppendChan stdout (show' ioerror)])
  2848.          (\s resps       -> [AppendChan stdout s])
  2849.     SearchError "Test"
  2850.     (11 reductions, 59 cells)
  2851.     ?
  2852.  
  2853. In each of the  examples  above,  the  failure  continuation  has  type
  2854. "FailCont" as defined by the following type  synonym  in  the  standard
  2855. prelude:
  2856.  
  2857.    type FailCont  =  IOError -> Dialogue
  2858.  
  2859. Similarly, the success continuation, which takes a string  representing
  2860. an input string and produces a new Dialogue has type "StrCont":
  2861.  
  2862.     type StrCont  =  String -> Dialogue
  2863.  
  2864. A third kind of continuation is needed for those requests which  return
  2865. a  response  of  the  form  "Success"  if  successful   (e.g.    output
  2866. requests).  In this case the continuation is simply another dialogue:
  2867.  
  2868.     type SuccCont =  Dialogue
  2869.  
  2870. The following list  gives  the  type  of  each  of  the  six  functions
  2871. corresponding to the six different kinds of I/O  request  described  in
  2872. the previous section.  Full definitions for each of these functions are
  2873. given in appendix B:
  2874.  
  2875.     readFile   :: String -> FailCont -> StrCont -> Dialogue
  2876.     writeFile  :: String -> String -> FailCont -> SuccCont -> Dialogue
  2877.     appendFile :: String -> String -> FailCont -> SuccCont -> Dialogue
  2878.     readChan   :: String -> FailCont -> StrCont  -> Dialogue
  2879.     appendChan :: String -> String -> FailCont -> SuccCont -> Dialogue
  2880.     echo       :: Bool -> FailCont -> SuccCont -> Dialogue
  2881.  
  2882. As an illustration of the use of these functions, we show how  each  of
  2883. the example programs from the previous section can be  rewritten  using
  2884. the  continuation  based  style  of  I/O,  starting  with  the  program
  2885. "helloWorld":
  2886.  
  2887.     helloWorld :: Dialogue
  2888.     helloWorld  = appendChan stdout "hello, world" abort done
  2889.  
  2890. In this case, the explicit type declaration is  not  actually  required
  2891. since the type of the expression is completely determined by  the  type
  2892. of "appendChan".  The failure continuation "abort" is equivalent to the
  2893. function "(\ioerror resps -> [])" described above  and  terminates  the
  2894. program if an error occurs without any further action.   In  a  similar
  2895. way, "done"  is  the  trivial  dialogue  which  terminates  immediately
  2896. without any action.   Both of these values are defined in the  standard
  2897. prelude:
  2898.  
  2899.    done         :: Dialogue
  2900.    done resps    = []
  2901.  
  2902.    abort        :: FailCont
  2903.    abort ioerror = done
  2904.  
  2905. Using the same approach, the "showFile" and "main"  programs  from  the
  2906. previous section are written as:
  2907.  
  2908.     showFile :: String -> Dialogue
  2909.     showFile name
  2910.      = readFile name (\ioerror -> appendChan stdout
  2911.                                      ("Can't open " ++ name) abort done)
  2912.                      (\contents-> appendChan stdout contents abort done)
  2913.  
  2914.     main :: Dialogue
  2915.     main  = appendChan stdout "Please type a filename: " abort
  2916.             (readChan stdin abort
  2917.             (\userInput -> let (name : _) = lines userInput in
  2918.              readFile name
  2919.               (\ioerror  -> appendChan stdout ("Can't open " ++ name)
  2920.                                 abort done)
  2921.               (\contents -> appendChan stdout contents abort done)))
  2922.  
  2923.  
  2924. .ST 12.3 Interactive programs
  2925. -------------------------
  2926. One of the principal motivations for including facilities  for  I/O  in
  2927. Gofer programs was to provide a way of using  interactive  programs  as
  2928. described in [1].  An interactive program is represented by a  function
  2929. of type String -> String mapping an input string of characters  entered
  2930. at the keyboard into an output string to be displayed on the screen.
  2931.  
  2932. There are two functions defined in the standard prelude  which  can  be
  2933. used to `execute' functions of this kind as interactive programs:
  2934.  
  2935.   o  "interact f" executes f::String->String as an interactive  program
  2936.      with echo on.  This  means  that  characters  are  read  from  the
  2937.      keyboard a line at a time.  The usual editing characters  such  as
  2938.      backspace can be used to correct mistakes which are noticed before
  2939.      the return key is pressed at the end  of  each  line.   The  input
  2940.      stream can be terminated by typing an end of file character at the
  2941.      beginning of a line:
  2942.  
  2943.          ? interact (map toUpper)
  2944.          This text was entered using the interact function
  2945.          THIS TEXT WAS ENTERED USING THE INTERACT FUNCTION
  2946.          ^Z
  2947.          (874 reductions, 1037 cells)
  2948.          ?
  2949.  
  2950.   o  "run f" behaves like "interact f" except that echo is turned  off.
  2951.      In this case, the only way of terminating the input stream without
  2952.      reaching the end of the string produced  by  "f"  is  to  use  the
  2953.      interrupt key:
  2954.  
  2955.          ? run (map toUpper)     
  2956.          ALTHOUGH THIS IS ENTERED IN LOWER CASE, IT STILL
  2957.          APPEARS IN UPPER CASE !
  2958.          {Interrupted!}
  2959.  
  2960.          (1227 reductions, 1463 cells)
  2961.          ?
  2962.  
  2963. [ASIDE: of these two functions, only "interact" is also included in the
  2964. standard prelude for Haskell, although "run" may also  be  added  to  a
  2965. Haskell system using the definition below.]
  2966.  
  2967. The definitions of "interact" and "run"  provide  further  examples  of
  2968. Gofer programs using simple I/O facilities:
  2969.  
  2970.     interact        :: (String -> String) -> Dialogue
  2971.     interact f       = readChan stdin abort
  2972.                             (\s -> appendChan stdout (f s) abort done)
  2973.  
  2974.     run             :: (String -> String) -> Dialogue
  2975.     run f            = echo False abort (interact f)
  2976.  
  2977. [EXERCISE for the interested reader:  construct alternative definitions
  2978. for these functions using the stream based approach from section 12.1.]
  2979.  
  2980. .pa
  2981. .co-------------------------------------------------------------------|
  2982. .>ch13
  2983. .ST 13. LAYOUT
  2984.  
  2985. .ST 13.1 Comments
  2986. -------------
  2987. Comments provide an informal but useful way  of  annotating  a  program
  2988. with  a  description  of  its  purpose,  structure   and   development.
  2989. Following  the  definition  of  Haskell,  two  styles  of  comment  are
  2990. supported by Gofer:
  2991.  
  2992.   o  A one line comment begins with the  two  characters  "--"  and  is
  2993.      terminated at the end of the same line.   Note  that  an  operator
  2994.      symbol cannot begin with "--" as  this  will  be  treated  as  the
  2995.      beginning of a comment.  It is however possible  to  use  the  two
  2996.      characters "--" at any other position within an  operator  symbol.
  2997.      Thus a line such as:
  2998.  
  2999.                            (xs ++ ys) -- xs
  3000.  
  3001.      includes a comment and will actually be treated as if the line had
  3002.      been written:
  3003.                                (xs ++ ys)
  3004.  
  3005.      Whereas the line:
  3006.  
  3007.                            xs >--> ys >--> zs
  3008.  
  3009.      does not contain any comments (although it  will  cause  an  error
  3010.      unless ">-->" has been defined  using  an  appropriate  infixl  or
  3011.      infixr declaration).
  3012.  
  3013.   o  A nested comment begins with the characters "{-",  ends  with  the
  3014.      characters "-}" and may span  any  number  of  lines.   [N.B.  the
  3015.      initial "{-" string  cannot  overlap  with  the  terminating  "-}"
  3016.      string so that the shortest possible nested comment is "{--}", and
  3017.      not "{-}"].  An unterminated nested comment will be treated as  an
  3018.      error.
  3019.  
  3020.      As the name suggests, comments of this kind may be nested so  that
  3021.      "{- {- ... -} ... {- ... -} -}" is treated as  a  single  comment.
  3022.      This makes nested comments particularly convenient  for  enclosing
  3023.      parts  of  a  program  which  may  already  contain  other  nested
  3024.      comments.
  3025.  
  3026. Both kinds of comment may be used in expressions entered directly  into
  3027. the Gofer system, or more usually, in files of definitions loaded  into
  3028. Gofer.  The two  styles  of  comment  may  be  mixed  within  the  same
  3029. expression or program, remembering that the string "--" has no  special
  3030. significance within a nested comment and that the strings "{-" and "-}"
  3031. have no special significance in a single line comment.  Thus:
  3032.  
  3033.             [ 2, -- {-                 [ 2, {-
  3034.               3, -- -}                   -- -} 3,
  3035.               4 ]                        4 ]
  3036.  
  3037. are both equivalent to the list expression [2,3,4].
  3038.  
  3039.  
  3040. .ST 13.2 The layout rule
  3041. --------------------
  3042. In a tradition dating back at least a quarter of a century to  Landin's
  3043. ISWIM family of languages,  most  Gofer  programs  use  indentation  to
  3044. indicate the structure of a program.  For example, in a definition such
  3045. as:
  3046.  
  3047.                     f x y = g (x + w)
  3048.                             where g u = u + v
  3049.                                         where v = u * u
  3050.                                   w   = 2 + y
  3051.  
  3052. it is clear from the layout that the definition of w is intended to  be
  3053. local to f rather than to g.  Another example  where  layout  plays  an
  3054. important role is in distinguishing the two definitions:
  3055.  
  3056.          example x y z = a + b       example x y z = a + b
  3057.                where a = f x y             where a   = f x
  3058.                      b = g z                     y b = g z
  3059.  
  3060. There are three situations in Gofer where indentation is typically used
  3061. to determine the structure of a program:
  3062.  
  3063.   o  At the top-level of a file of definitions.
  3064.  
  3065.   o  In a group of local declarations following either of the  keywords
  3066.      "let" or "where".
  3067.  
  3068.   o  In a group of alternatives in a  case  expression,  following  the
  3069.      keyword "of".
  3070.  
  3071. In each case, Gofer actually expects to find a list of  items  enclosed
  3072. between braces `{' and `}' with individual  items  separated  from  one
  3073. another by semicolons `;'.  However, if the leading brace is not  found
  3074. then Gofer uses the layout rule described below to arrange for `{', `}'
  3075. and `;' tokens to be  inserted  into  the  input  stream  automatically
  3076. according to the indentation of each line.
  3077.  
  3078. In this way, the first example above will in fact be treated as if the
  3079. user had entered:
  3080.  
  3081.                     f x y = g (x + w)
  3082.                             where {g u = u + v
  3083.                                          where {v = u * u
  3084.                                   }; w   = 2 + y
  3085.                     }
  3086.  
  3087. or, equivalently, just:
  3088.  
  3089.   f x y = g (x + w) where {g u = u + v where {v = u * u}; w = 2 + y}
  3090.  
  3091. where the additional punctuation using the `{', `}' and `;'  characters
  3092. makes the intended grouping clear, regardless of indentation.
  3093.  
  3094. .cc 2
  3095. The layout rule used in Gofer is the same as that of Haskell,  and  can
  3096. be described as follows:
  3097.  
  3098.   o  An opening brace `{' is inserted in front of the  first  token  at
  3099.      the beginning of a file or following one of the keywords  "where",
  3100.      "let" or "of", unless that token is itself an opening brace.
  3101.  
  3102.   o  A `;' token is inserted  in  front  of  the  first  token  in  any
  3103.      subsequent line with exactly the same indentation as the token  in
  3104.      front of which the opening brace was inserted.
  3105.  
  3106.   o  The layout rule ends and a `}' token is inserted in front  of  the
  3107.      first token in a subsequent line  whose  indentation  is  strictly
  3108.      less than that of the token in front of which  the  opening  brace
  3109.      was inserted.
  3110.  
  3111.   o  A closing brace `}' will also be inserted at any  point  where  an
  3112.      otherwise unexpected token is encountered.  This part of the rule
  3113.      makes it possible to use expressions such as:
  3114.  
  3115.                        let a = fact 12 in a+a
  3116.  
  3117.      without needing to use the layout characters explicitly as in:
  3118.  
  3119.                       let {a = fact 12} in a+a.
  3120.  
  3121.   o  Lines containing only whitespace (blanks and tabs) and comments do
  3122.      not affect the use of the layout rule.
  3123.  
  3124.   o  For the purposes of determining the indentation of each line in  a
  3125.      file, tab stops are assumed to be placed every 8 characters,  with
  3126.      the leftmost tab stop in column 9.  Each tab character inserts one
  3127.      or more spaces as necessary to move to the next tab stop.
  3128.  
  3129.   o  The indentation of the end of file token is zero.
  3130.  
  3131. The following (rather contrived) program, is based on an example in the
  3132. Haskell report [5], and provides an extended example of the use of  the
  3133. layout rule.  A file containing the following definitions:
  3134.  
  3135.     data Stack a = Empty
  3136.                  | MkStack a (Stack a)
  3137.  
  3138.     push    :: a -> Stack a -> Stack a
  3139.     push x s = MkStack x s
  3140.  
  3141.     size  :: Stack a -> Int
  3142.     size s = length (stkToList s) where
  3143.                stkToList Empty         = []
  3144.                stkToList (MkStack x s) = x:xs where xs = stkToList s
  3145.  
  3146.     pop :: Stack a -> (a, Stack a)
  3147.     pop (MkStack x s) = (x, case s of r -> i r where i x = x)
  3148.  
  3149.     top :: Stack a -> a
  3150.     top (MkStack x s) = x
  3151.  
  3152. will be treated by Gofer as if it has been written:
  3153.  
  3154.     {data Stack a = Empty
  3155.                   | MkStack a (Stack a)
  3156.  
  3157.     ;push    :: a -> Stack a -> Stack a
  3158.     ;push x s = MkStack x s
  3159.  
  3160.     ;size  :: Stack a -> Int
  3161.     ;size s = length (stkToList s) where
  3162.                {stkToList Empty = []
  3163.                ;stkToList (MkStack x s) = x:xs where {xs = stkToList s
  3164.  
  3165.     }};pop :: Stack a -> (a, Stack a)
  3166.     ;pop (MkStack x s) = (x, case s of {r -> i r where {i x = x}})
  3167.  
  3168.     ;top :: Stack a -> a
  3169.     ;top (MkStack x s) = x
  3170.     }
  3171.  
  3172. Note that some of the more sophisticated forms of expression cannot  be
  3173. written on a single line (and hence entered  directly  into  the  Gofer
  3174. system) without explicit use of the layout characters `{', `}' and `;':
  3175.  
  3176.     ? len [1..10] where len [] = 0;  len (x:xs) = 1 + len xs
  3177.     10
  3178.     (81 reductions, 108 cells)
  3179.  
  3180.     ? f True where f x = case x of True->n where {n=not x}; False->True
  3181.     False
  3182.     (4 reductions, 11 cells)
  3183.  
  3184.     ?
  3185.  
  3186. One situation in which the layout  rule  can  cause  problems  is  with
  3187. top-level definitions.  For example, the two lines:
  3188.  
  3189.    f x  = 1 + x
  3190.     g y = 1 - y
  3191.  
  3192. will be treated as a single line "f x = 1 + x g y = 1 - y", which  will
  3193. cause a syntax  error.   This  kind  of  problem  becomes  rather  more
  3194. difficult to spot if the two definitions are not on  subsequent  lines,
  3195. particularly if they are separated by several lines of  comments.   For
  3196. this reason, it is usually a good  idea  to  ensure  that  all  of  the
  3197. top-level definitions in a file start in the  same  column  (the  first
  3198. column is usually the most convenient).  COBOL and Fortran  programmers
  3199. are not likely to find this problem too distressing :-)
  3200. .pa
  3201. .on
  3202. .co-------------------------------------------------------------------|
  3203. .>ch14
  3204. .ST 14. OVERLOADING IN GOFER
  3205.  
  3206. One of the biggest differences between Gofer and most other programming
  3207. languages  (with  the  exception  of  Haskell)  is  the   approach   to
  3208. overloading; enabling the definition and use of functions in which  the
  3209. meaning of a function symbol may depend on the types of its arguments.
  3210.  
  3211. Like Haskell, overloading in Gofer is based around  a  system  of  type
  3212. classes which allow overloaded functions to be  grouped  together  into
  3213. related groups  of  functions.   Whilst  the  precise  details  of  the
  3214. approach to type classes used by  Gofer are quite  different from those
  3215. of Haskell,  both rely on the same basic ideas and use a similar syntax
  3216. for defining and using type classes.   It would therefore seem possible
  3217. that experience gained with the overloading system in one language  can
  3218. readily by applied to the other.
  3219.  
  3220. The differences embodied in the Gofer system of classes  stem  from  my
  3221. own, theoretically based investigations into `qualified types' some  of
  3222. which is detailed in references [8-12].  In my  personal  opinion,  the
  3223. Gofer system has some significant advantages over the Haskell  approach
  3224. (see [12] for details) and one of the principal motivations behind  the
  3225. implementation to Gofer was to provide a way of  testing  such  claims.
  3226. One fact which I believe has already been established  using  Gofer  is
  3227. that the use and implementation of overloaded functions need  not  have
  3228. the significant effect on performance that was anticipated  with  early
  3229. implementations of Haskell.
  3230.  
  3231. This section outlines  the  system  of  type  classes  used  in  Gofer,
  3232. indicating briefly how they can be used and how they are implemented.
  3233.  
  3234.  
  3235. .ST 14.1 Type classes and predicates
  3236. --------------------------------
  3237. A type class can be thought of as a family of types (or more  generally
  3238. as a family of tuples of types) whose elements are called instances  of
  3239. the class.  If C is the name of  an  n-parameter  type  class  then  an
  3240. expression of the form C t1 t2 ... tn where t1, t2, ...,  tn  are  type
  3241. expressions is called a predicate and represents the assertion that the
  3242. specified tuple of types is an instance of the class C.
  3243.  
  3244. Given a polymorphic function (e.g. map::(a->b)->[a]->[b]), we are  free
  3245. to use the function at any type which can be obtained  by  substituting
  3246. arbitrary types for each of the type variables in its type.  In  Gofer,
  3247. a type expression may be qualified by  one  or  more  predicates  which
  3248. restrict the range of types at which a value can be used:
  3249.  
  3250. e.g. a function of type C a => a -> a -> a can be treated as a function
  3251.      of type t -> t -> t for any instance t of the class C.
  3252.  
  3253. The predicate C a in the type expression in  the  previous  example  is
  3254. called the context of the type.  Contexts may  contain  more  than  one
  3255. predicate in which case the predicates involved must  be  separated  by
  3256. commas and the context enclosed in parentheses as in (C a, D  b).   The
  3257. empty context is written () and any type expression t is equivalent  to
  3258. the qualified type () => t.  For uniformity, a context  with  only  one
  3259. element may also be enclosed by parentheses.
  3260.  
  3261. For technical reasons, type synonyms are  not  currently  permitted  in
  3262. predicates.  This is consistent with the use of predicates in  Haskell,
  3263. but may be relaxed, at least in certain cases,  in  later  versions  of
  3264. Gofer.
  3265.  
  3266.  
  3267. .ST 14.2 The type class Eq
  3268. ----------------------
  3269. The type class Eq is a simple and useful example, whose  instances  are
  3270. precisely those types whose elements can be tested for  equality.   The
  3271. declaration of this class given in the standard prelude is as follows:
  3272.  
  3273.     class Eq a where
  3274.         (==), (/=) :: a -> a -> Bool
  3275.         x /= y      = not (x == y)
  3276.  
  3277. There are three parts in any class declaration.   For  this  particular
  3278. example we have:
  3279.  
  3280.   o  The first line (called the `header') of the declaration introduces
  3281.      a name Eq for the  class  and  indicates  that  it  has  a  single
  3282.      parameter, represented by the type variable a.
  3283.  
  3284.   o  The  second  line  of  the  declaration  (the  `signature   part')
  3285.      indicates that there are functions denoted by the operator symbols
  3286.      (==) and (/=) of type a -> a -> Bool for each instance a of  class
  3287.      Eq.  Using the notation introduced in the previous  section,  both
  3288.      of these operators have type:
  3289.  
  3290.                       Eq a => a -> a -> Bool
  3291.  
  3292.      These functions are called the `members' (or  `member  functions')
  3293.      of the class.  [This terminology, taken from  Haskell,  is  rather
  3294.      unfortunate; thinking of a type class  as  a  set  of  types,  the
  3295.      elements of the class are called `instances', whilst the `members'
  3296.      of the class correspond more closely  to  the  instance  variables
  3297.      that are used in the terminology of object-oriented programming.]
  3298.  
  3299.      The intention is that the (==) function will be used to  implement
  3300.      an equality test for each instance of the  class,  with  the  (/=)
  3301.      operator providing the  corresponding  inequality  function.   The
  3302.      ability to include related groups of  functions  within  a  single
  3303.      type class in this way is a useful tool in program design.
  3304.  
  3305.   o  The  third  line  of   the   class   declaration   (the   `default
  3306.      definitions') provides a default definition of the  (/=)  operator
  3307.      in terms of the (==) operator.  Thus it is only necessary to  give
  3308.      a definition for the (==) operator in order to define all  of  the
  3309.      member functions for the class Eq.  It  is  possible  to  override
  3310.      default member definitions by giving an alternative definition  as
  3311.      appropriate for specific instances of the class.
  3312.  
  3313.  
  3314. .ST 14.2.1 Implicit overloading
  3315. ---------------------------
  3316. Member functions are clearly marked as overloaded  functions  by  their
  3317. definition as part of a class declaration, but this is not the only way
  3318. in which overloaded  functions  occur  in  Gofer;  the  restriction  to
  3319. particular instances of a type class is also carried over into the type
  3320. of any function defined either directly or indirectly in terms  of  the
  3321. member functions of that class.  For example, the  types  inferred  for
  3322. the following two functions:
  3323.  
  3324.     x  `elem`   xs   =   any (x==) xs
  3325.     xs `subset` ys   =   all (`elem` ys) xs
  3326.  
  3327. are:
  3328.  
  3329.     elem   :: Eq a => a -> [a] -> Bool
  3330.     subset :: Eq a => [a] -> [a] -> Bool
  3331.  
  3332. [ASIDE: On the  other  hand,  if  none  of  the  functions  used  in  a
  3333. particular expression or definition are overloaded then there will  not
  3334. be any overloading in the corresponding value.  Gofer does not  support
  3335. the concept of implicit overloading used  in  some  languages  where  a
  3336. value of a particular type might automatically be coerced to a value of
  3337. some supertype.  An example of this would be the automatic  translation
  3338. of a badly typed expression "1.0 == 1" to a  well-typed  expression  of
  3339. the form "1.0 == float 1" for some  (potentially  overloaded)  coercion
  3340. function "float" mapping numeric values to elements of type Float.]
  3341.  
  3342. Note also that the types appearing in the context of a  qualified  type
  3343. reflect the types at which overloaded functions are used.  Thus:
  3344.  
  3345.     f x ys  =  [x] == ys
  3346.  
  3347. has type  Eq [a] => a -> [a] -> Bool, and not Eq a => a -> [a] -> Bool,
  3348. which is the type that would be assigned to "f" in a Haskell system.
  3349.  
  3350.  
  3351. .ST 14.2.2 Instances of class Eq
  3352. ----------------------------
  3353. Instances of a type class are defined  using  declarations  similar  to
  3354. those used to define  the  corresponding  type  class.   The  following
  3355. examples, taken from the standard prelude, give the definitions  for  a
  3356. number of simple instances of the class Eq:
  3357.  
  3358.     instance Eq Int  where  (==) = primEqInt
  3359.  
  3360.     instance Eq Bool where
  3361.         True  == True   =  True
  3362.         False == False  =  True
  3363.         _     == _      =  False
  3364.  
  3365.     instance Eq Char  where  c == d  =  ord c == ord d
  3366.  
  3367.     instance (Eq a, Eq b) => Eq (a,b) where
  3368.         (x,y) == (u,v)  =  x==u && y==v
  3369.  
  3370.     instance Eq a => Eq [a] where
  3371.         []     == []     =  True
  3372.         []     == (y:ys) =  False
  3373.         (x:xs) == []     =  False
  3374.         (x:xs) == (y:ys) =  x==y && xs==ys
  3375.  
  3376. The interpretation of these declarations is as follows:
  3377.  
  3378.   o  The first declaration  makes Int an instance  of  class  Eq.   The
  3379.      function "primEqInt" is a primitive Gofer function which tests the
  3380.      equality of two integer values and has type Int -> Int -> Bool.
  3381.  
  3382.   o  The second declaration makes  Bool an instance of  class Eq with a
  3383.      simple definition involving pattern matching.
  3384.  
  3385.   o  The third declaration makes Char an instance of  class  Eq.   This
  3386.      definition indicates that a pair of characters are equal  if  they
  3387.      have the same ASCII value,  which  is  obtained  using  the  "ord"
  3388.      function.  Note that the two occurrences of the symbol (==) in the
  3389.      equation:
  3390.  
  3391.                        c == d  =  ord c == ord d
  3392.  
  3393.      have  different  meanings;  the  first  denotes  equality  between
  3394.      characters (elements of type  Char),  whilst  the  second  denotes
  3395.      equality between integers (elements of type Int).
  3396.  
  3397.   o  The fourth declaration provides an equality  operation  on  pairs.
  3398.      Given two elements (x,y) and (u,v) of type (a,b) for some a, b, it
  3399.      must be possible to check that both x==u and y==v before we can be
  3400.      sure that the two pairs are indeed equal.  In other words, both  a
  3401.      and b must also be instances of Eq  in  order  to  make  (a,b)  an
  3402.      instance of Eq.  This requirement is described by the  first  line
  3403.      in the instance declaration using the expression:
  3404.  
  3405.                        (Eq a, Eq b) => Eq (a,b)
  3406.  
  3407.   o  The fifth declaration makes [a] an instance of Eq, whenever  a  is
  3408.      itself an instance  of  Eq  in  a  similar  way  to  the  previous
  3409.      example.  The context Eq a is used in the  last  equation  in  the
  3410.      declaration:
  3411.  
  3412.                      (x:xs) == (y:ys)  =  x==y && xs==ys
  3413.  
  3414.      which contains three occurrences of the (==) operator;  the  first
  3415.      and third are used to compare lists of type [a], whilst the second
  3416.      is used to compare elements of type a, using the instance Eq a.
  3417.  
  3418. Combining these five declarations, we obtain definitions for (==) on an
  3419. infinite  family  of  types  including  Int,  Char,  Bool,  (Int,Bool),
  3420. (Char,Int), [Char], (Bool,[Int]), [(Bool,Int)], etc...:
  3421.  
  3422.     ? 2 == 3                            -- using Eq Int
  3423.     False
  3424.     (2 reductions, 10 cells)
  3425.     ? (["Hello"],3) == (["Hello"],3)    -- using Eq ([[Char]],Int)
  3426.     True
  3427.     (31 reductions, 65 cells)
  3428.     ?
  3429.  
  3430. On the other hand, any attempt to use (==) to compare elements of  some
  3431. type not covered by a suitable instance declaration will result  in  an
  3432. error.  For example, the standard prelude does not define the  equality
  3433. operation on triples of values:
  3434.  
  3435.     ? (1,2,3) == (1,2,3)
  3436.     ERROR: Cannot derive instance in expression
  3437.     *** Expression        : (==) d125 (1,2,3) (1,2,3)
  3438.     *** Required instance : Eq (Int,Int,Int)
  3439.     ?
  3440.  
  3441. This can  be  solved  by  including  an  instance  declaration  of  the
  3442. following form into a file of definitions loaded into Gofer:
  3443.  
  3444.     instance (Eq a, Eq b, Eq c) => Eq (a,b,c) where
  3445.         (x,y,z) == (u,v,w)  =  x==u && y==v && z==w
  3446.  
  3447. Giving:
  3448.  
  3449.     ? (1,2,3) == (1,2,3)
  3450.     True
  3451.     (6 reductions, 20 cells)
  3452.     ?
  3453.  
  3454. In general, an instance declaration has the form:
  3455.  
  3456.              instance  context => predicate  where
  3457.                  definitions of member functions
  3458.  
  3459. The context part of the declaration gives a list  of  predicates  which
  3460. must be satisfied for the predicate on the right hand side of the  `=>'
  3461. sign to be valid.  Constant predicates (i.e. predicates  not  involving
  3462. any type variables) required by an instance declaration  (such  as  the
  3463. predicate Eq Int  required  by  the  third  declaration)  need  not  be
  3464. included in the context.  If the resulting context is empty (as in  the
  3465. first three declarations above) then it may be omitted,  together  with
  3466. the corresponding `=>' symbol.
  3467.  
  3468.  
  3469. .ST 14.2.3 Testing equality of represented values
  3470. ---------------------------------------------
  3471. Instances of  Eq  can  also  be  defined  for  other  types,  including
  3472. user-defined datatypes, and unlike the instances described  above,  the
  3473. definition of (==) need not be used to  determine  whether  the  values
  3474. being compared have the same structure; it  is  often  more  useful  to
  3475. check that they represent the same value.  As an example, suppose  that
  3476. we introduce a type constructor Set for representing  sets  of  values,
  3477. using a list to store the values held in the set:
  3478.  
  3479.     data Set a = Set [a]
  3480.  
  3481. As usual, we say that two sets are equal if they have the same members,
  3482. ignoring any repetitions or differences in the ordering of the elements
  3483. in the lists  representing  the  sets.   This  is  achieved  using  the
  3484. following instance declaration:
  3485.  
  3486.     instance Eq a => Eq (Set a) where
  3487.         Set xs == Set ys  =  xs `subset` ys  &&  ys `subset` xs
  3488.                              where xs `subset` ys = all (`elem` ys) xs
  3489.  
  3490. A couple of examples illustrate the use of this definition:
  3491.  
  3492.     ? Set [1,2,3] == Set [3,4,1]
  3493.     False
  3494.     (49 reductions, 89 cells)
  3495.     ? Set [1,2,3] == Set [1,2,2,2,1,3]
  3496.     True
  3497.     (157 reductions, 240 cells)
  3498.     ? 
  3499.  
  3500.  
  3501. .ST 14.2.4 Instance declarations without members
  3502. --------------------------------------------
  3503. It is possible to give an instance declaration without  specifying  any
  3504. definitions for the member functions of the class.  For example:
  3505.  
  3506.     instance Eq ()
  3507.  
  3508. In this case, the definition of  (==) for the instance  Eq ()  is  left
  3509. completely undefined, and hence so is the definition of (/=), which  is
  3510. defined in terms of (==):
  3511.  
  3512.     ? () == ()
  3513.     {undefined_member (==)}
  3514.     (3 reductions, 34 cells)
  3515.     ? () /= ()
  3516.     {undefined_member (==)}
  3517.     (4 reductions, 36 cells)
  3518.     ? 
  3519.  
  3520.  
  3521. .ST 14.2.5 Equality on function types
  3522. ---------------------------------
  3523. If an expression requires an  instance  of  a  class  which  cannot  be
  3524. obtained using the rules in the given instance  declarations,  then  an
  3525. error message will be produced when  the  expression  is  type-checked.
  3526. For example, in general there is no sensible way to  determine  when  a
  3527. pair of functions are equal, and the standard prelude does not  include
  3528. a definition for an instance of the form Eq (a -> b) for  any  types  a
  3529. and b:
  3530.  
  3531.     ? (1==) == (\x->1==x)
  3532.     ERROR: Cannot derive instance in expression
  3533.     *** Expression        : (==) d148 ((==) {dict} 1) (\x->(==) {dict} 1 x)
  3534.     *** Required instance : Eq (Int -> Bool)
  3535.  
  3536.     ?
  3537.  
  3538. If for some reason, you would prefer this kind of error to  produce  an
  3539. error message when an expression is evaluated, rather than when  it  is
  3540. type-checked, you can  use  an  instance  declaration  to  specify  the
  3541. required behaviour.  For example:
  3542.  
  3543.     instance Eq (a -> b) where 
  3544.         (==) = error "Equality not defined between functions"
  3545.  
  3546. Evaluating the previous expression once this instance  declaration  has
  3547. been included now produces the following result:
  3548.  
  3549.     ? (1==) == (\x->1==x)
  3550.     {error "Equality not defined between functions"}
  3551.     (42 reductions, 173 cells)
  3552.     ? 
  3553.  
  3554. A limited form of equality can be defined for functions of type  (a->b)
  3555. if a has only finitely many elements, such as the boolean type Bool:
  3556.  
  3557.     instance Eq a => Eq (Bool -> a) where
  3558.         f == g   =   f False == g False   &&   f True == g True
  3559.  
  3560. [ASIDE: This instance declaration would not be accepted  in  a  Haskell
  3561. program which insists that the predicate  on  the  right  of  the  `=>'
  3562. symbol contains precisely one type constructor symbol.]
  3563.  
  3564. Using this instance declaration once for each argument, we can now test
  3565. two functions taking boolean arguments for equality (assuming of course
  3566. that their result type is also an instance of Eq).
  3567.  
  3568.     ? (&&) == (||)
  3569.     False
  3570.     (9 reductions, 21 cells)
  3571.     ? not == (\x -> if x then False else True)
  3572.     True
  3573.     (8 reductions, 16 cells)
  3574.     ? (&&) == (\x y-> if x then y else False)
  3575.     True
  3576.     (16 reductions, 30 cells)
  3577.     ? 
  3578.  
  3579.  
  3580. .ST 14.2.6 Non-overlapping instances
  3581. --------------------------------
  3582. Other instance declarations for types of the form a -> b can be used at
  3583. the same time, so  long  as  no  pair  of  declarations  overlap.   For
  3584. example, adding the following instance declaration
  3585.  
  3586.     instance Eq a => Eq (() -> a)  where  f == g  =  f () == g ()
  3587.  
  3588. enables us to evaluate expressions such as:
  3589.  
  3590.     ? (\()->"Hello") == const "Hello"
  3591.     True
  3592.     (30 reductions, 55 cells)
  3593.     ? 
  3594.  
  3595. If however, we try to use instance declarations for types of  the  form
  3596. (a -> b) and (Bool -> a) at the same time, then Gofer produces an error
  3597. message similar to the following:
  3598.  
  3599.     ERROR "file" (line 37): Overlapping instances for class "Eq"
  3600.     *** This instance   : Eq (a -> b)
  3601.     *** Overlaps with   : Eq (Bool -> a)
  3602.     *** Common instance : Eq (Bool -> a)
  3603.  
  3604.     ? 
  3605.  
  3606. indicating that, given the task of testing two values of type (Bool->a)
  3607. for equality, there are (at least) two definitions of (==)  that  could
  3608. be used, with potentially different  results  being  obtained  in  each
  3609. case.
  3610.  
  3611. Here is a further example of the use of non-overlapping instances of  a
  3612. class to define a function "cat" (inspired by the unix (tm) command  of
  3613. the same name) which uses the I/O facilities  of  Gofer  to  print  the
  3614. contents of one or more files on the terminal:
  3615.  
  3616.     class    Cat a        where cat  :: a -> Dialogue
  3617.     instance Cat [Char]   where cat n = showFile n done
  3618.     instance Cat [[Char]] where cat   = foldr showFile done
  3619.  
  3620.     showFile name cont = readFile name abort
  3621.                              (\s->appendChan stdout s abort cont)
  3622.  
  3623. Given these declarations, an expression of the form:
  3624.  
  3625.                             cat "file"
  3626.  
  3627. can be used to display the contents of the named file, whilst a list of
  3628. files can be printed one after the other using  an  expression  of  the
  3629. form:
  3630.  
  3631.                cat ["file1", "file2", ..., "filen"].
  3632.  
  3633.  
  3634. .ST 14.3 Dictionaries
  3635. -----------------
  3636. In order to understand some of the messages produced by Gofer, as  well
  3637. as  some  of  the  more  subtle  problems  associated  with  overloaded
  3638. functions, it is useful to have a  rough  idea  of  the  way  in  which
  3639. overloaded functions are implemented.
  3640.  
  3641. The basic idea is that a function with a qualified type context => type
  3642. where context is a non-empty list of predicates  is  implemented  by  a
  3643. function which takes an  extra  argument  for  each  predicate  in  the
  3644. context.  When the function is used, each of these parameters is filled
  3645. by a `dictionary'  which  gives  the  values  of  each  of  the  member
  3646. functions in the appropriate class.  None of these extra parameters  is
  3647. entered by the programmer.  Instead, they  are  inserted  automatically
  3648. during type-checking.
  3649.  
  3650. For the class Eq, each dictionary has at least two elements  containing
  3651. definitions for each of the functions (==) and (/=).  A dictionary  for
  3652. an instance of Eq can be depicted by a diagram of the form:
  3653.  
  3654.                      +--------+--------+---------
  3655.                      |        |        |
  3656.                      |  (==)  |  (/=)  |  .....
  3657.                      |        |        |
  3658.                      +--------+--------+---------
  3659.  
  3660. In order to produce useful error messages and indicate the way in which
  3661. dictionary expressions are being used, Gofer uses a number  of  special
  3662. notations for printing expressions involving dictionaries:
  3663.  
  3664.    (#1 d)   selects the first element of the dictionary d
  3665.  
  3666.    (#2 d)   selects the second element of the dictionary d
  3667.  
  3668.    (#n d)   selects the nth element of the dictionary d
  3669.             (note that (#0 d) is equivalent to the dictionary d).
  3670.  
  3671.    {dict}   denotes a specific dictionary (the contents are not
  3672.             displayed).
  3673.  
  3674.    dnnn     a dictionary variable representing an unknown dictionary is
  3675.             printed as a lower case letter `d' followed by an  integer;
  3676.             e.g. d231.
  3677.  
  3678. Note that, whilst these notations are used in output produced by  Gofer
  3679. and in the following explanations, they cannot be entered directly into
  3680. Gofer expressions or programs -- even if you use  a  variable  such  as
  3681. "d1" in an expression, Gofer will not confuse this  with  a  dictionary
  3682. variable with the same name (although Gofer might confuse you by  using
  3683. the same name in two different contexts!).
  3684.  
  3685. Using these notations, the member functions (==) and (/=) of the  class
  3686. Eq behave as if they were defined by the expressions:
  3687.  
  3688.     (==) d1  =  (#1 d1)
  3689.     (/=) d1  =  (#2 d1)
  3690.  
  3691. To understand how these definitions work, we need to take a look  at  a
  3692. specific dictionary.  Following the original instance declaration  used
  3693. for Eq Int, the corresponding dictionary is:
  3694.  
  3695.                     d :: Eq Int
  3696.                     +------------+------------+
  3697.                     |            |            |
  3698.                     | primEqInt  |  defNeq d  |
  3699.                     |            |            |
  3700.                     +------------+------------+
  3701.  
  3702. Note that the  dictionary  variable  d  is  used  as  a  name  for  the
  3703. dictionary in this diagram, indicating how values within  a  dictionary
  3704. can include references to the same dictionary.
  3705.  
  3706. [ASIDE: It turns out that predicates  play  a  very  similar  role  for
  3707. dictionaries as types play for normal values.  This motivates  our  use
  3708. of the notation d :: Eq Int to indicate that d is a dictionary for  the
  3709. instance Eq Int.  One difference between these, particularly  important
  3710. for theoretical work, is that dictionary values are uniquely determined
  3711. by predicates; if d1::p and d2::p for some predicate p, then d1 = d2.]
  3712.  
  3713. The value held in the first element of the dictionary is the  primitive
  3714. equality function on  integers,  "primEqInt".   The  following  diagram
  3715. shows how the dictionary is used to evaluate the expression "2  ==  3".
  3716. Note that this expression will first be translated to  "(==) d 2 3"  by
  3717. the type checker.  The evaluation then proceeds as follows:
  3718.  
  3719.     (==) d 2 3  ==>  (#1 d) 2 3
  3720.                 ==>  primEqInt 2 3
  3721.                 ==>  False
  3722.  
  3723. The second element of the  dictionary  is  a  little  more  interesting
  3724. because it uses the default definition for (/=) given in  the  original
  3725. class definition  which,  after  translation,  is  represented  by  the
  3726. function "defNeq" defined by:
  3727.  
  3728.     defNeq d1 x y = not ((==) d1 x y)
  3729.  
  3730. Notice the way in which the  extra  dictionary  parameter  is  used  to
  3731. obtain the appropriate overloading.  For  example,  evaluation  of  the
  3732. expression  "2 /= 3", which  becomes  "(/=) d 2 3"  after  translation,
  3733. proceeds as follows:
  3734.  
  3735.     (/=) d 2 3  ==>  (#2 d) 2 3
  3736.                 ==>  defNeq d 2 3
  3737.                 ==>  not ((==) d 2 3)
  3738.                 ==>  not ((#1 d) 2 3)
  3739.                 ==>  not (primEqInt 2 3)
  3740.                 ==>  not False
  3741.                 ==>  True
  3742.  
  3743. [Clearly there is some scope for optimisation here; whilst  the  actual
  3744. reduction sequences used by Gofer are equivalent to  those  illustrated
  3745. above, the precise details are a little different.]
  3746.  
  3747. If an  instance  is  obtained  from  an  instance  declaration  with  a
  3748. non-empty context, then the basic two element dictionary  used  in  the
  3749. examples above is extended with an  extra  dictionary  value  for  each
  3750. predicate in the context.  As an example, the diagram below  shows  the
  3751. dictionaries that will be created  from  the  instance  definitions  in
  3752. section 14.2.2  for  the  instance  Eq  (Int,  [Int]).   The  functions
  3753. "eqPair" and "eqList" which are used in these dictionaries are obtained
  3754. from the definitions of (==) given in the instance declarations for  Eq
  3755. (a,b) and Eq [a] respectively:
  3756.  
  3757.     eqPair d (x,y) (u,v)   = (==) (#3 d) x u && (==) (#4 d) y v
  3758.  
  3759.     eqList d [] []         = True
  3760.     eqList d []     (y:ys) = False
  3761.     eqList d (x:xs) []     = False
  3762.     eqList d (x:xs) (y:ys) = (==) (#3 d) x y && (==) d xs ys
  3763.  
  3764. The dictionary structure for Eq (Int, [Int]) is as follows.  Note  that
  3765. the Gofer system ensures that there is at most  one  dictionary  for  a
  3766. particular instance of a class, and that the dictionary d1 :: Eq Int in
  3767. this system is automatically shared between d2 and d3:
  3768.  
  3769.    d3 :: Eq (Int, [Int])
  3770.    +------------+------------+------------+------------+
  3771.    |            |            |            |            |
  3772.    | eqPair d3  | defNeq d3  | d1::Eq Int |d2::Eq [Int]|
  3773.    |            |            |            |            |
  3774.    +------------+------------+-----+------+-----+------+
  3775.                                    |            |
  3776.                     +--------------+            |
  3777.                     |                           |
  3778.                     |        d2 :: Eq [Int]     V 
  3779.                     |        +------------+------------+------------+
  3780.                     |        |            |            |            |
  3781.                     |        | eqList d2  | defNeq d2  | d1::Eq Int |
  3782.                     |        |            |            |            |
  3783.                     |        +------------+------------+-----+------+
  3784.                     |                                        |
  3785.        d1 :: Eq Int V                                        |
  3786.        +------------+------------+                           |
  3787.        |            |            |                           |
  3788.        | primEqInt  | defNeq d1  |<--------------------------+
  3789.        |            |            |
  3790.        +------------+------------+
  3791.  
  3792. Once again, it may be useful to see how these definitions are  used  to
  3793. evaluate  the  expression   "(2,[1])   ==   (2,[1,3])"   which,   after
  3794. translation, becomes "(==) d3 (2,[1]) (2,[1,3])":
  3795.  
  3796.     (==) d3 (2,[1]) (2,[1,3])
  3797.              ==>   (#1 d3) (2,[1]) (2,[1,3])
  3798.              ==>   eqPair d3 (2,[1]) (2,[1,3])
  3799.              ==>   (==) (#3 d3) 2 2  &&  (==) (#4 d3) [1] [1,3]
  3800.              ==>   (==) d1 2 2       &&  (==) (#4 d3) [1] [1,3]
  3801.              ==>   (#1 d1) 2 2       &&  (==) (#4 d3) [1] [1,3]
  3802.              ==>   primEqInt 2 2     &&  (==) (#4 d3) [1] [1,3]
  3803.              ==>   True              &&  (==) (#4 d3) [1] [1,3]
  3804.              ==>   (==) (#4 d3) [1] [1,3]
  3805.              ==>   (==) d2 [1] [1,3]
  3806.              ==>   (#1 d2) [1] [1,3]
  3807.              ==>   eqList d2 [1] [1,3]
  3808.              ==>   (==) (#3 d2) 1 1  &&  (==) d2 [] [3]
  3809.              ==>   (==) d1 1 1       &&  (==) d2 [] [3]
  3810.              ==>   (#1 d1) 1 1       &&  (==) d2 [] [3]
  3811.              ==>   primEqInt 1 1     &&  (==) d2 [] [3]
  3812.              ==>   True              &&  (==) d2 [] [3]
  3813.              ==>   (==) d2 [] [3]
  3814.              ==>   False
  3815.  
  3816.  
  3817. .ST 14.3.1 Superclasses
  3818. -------------------
  3819. In general, a type class declaration has the form:
  3820.  
  3821.              class  context => Class a1 ... an  where
  3822.                  type declarations for member functions
  3823.                  default definitions of member functions
  3824.  
  3825. where Class is the name of the new type class which takes n  arguments,
  3826. represented by distinct type variables a1, ..., an.  As in the case  of
  3827. instance declarations, the context that appears on the left  hand  side
  3828. of the `=>'  symbol  specifies  a  list  of  predicates  that  must  be
  3829. satisfied in order to construct any instance of "Class".
  3830.  
  3831. The predicates in the context part of a class  declaration  are  called
  3832. the superclasses of Class.  This  terminology  is  taken  from  Haskell
  3833. where all classes have a single parameter and each of the predicates in
  3834. the context part of a class declaration has the  form  C  a1;  in  this
  3835. situation, any instance of Class must also be an instance of each class
  3836. C named in the context.   In  other  words,  each  such  C  contains  a
  3837. superset of the types in Class.
  3838.  
  3839. As an example of a class declaration with a non-empty context, consider
  3840. the following declaration from the standard prelude which introduces  a
  3841. class Ord whose instances are types  with  both  strict  (<),  (>)  and
  3842. non-strict  (<=),  (>=)  versions  of  an  ordering  defined  on  their
  3843. elements:
  3844.  
  3845.     class Eq a => Ord a where
  3846.         (<), (<=), (>), (>=) :: a -> a -> Bool
  3847.         max, min             :: a -> a -> a
  3848.  
  3849.         x <  y            = x <= y && x /= y
  3850.         x >= y            = y <= x
  3851.         x >  y            = y < x
  3852.  
  3853.         max x y | x >= y  = x
  3854.                 | y >= x  = y
  3855.         min x y | x <= y  = x
  3856.                 | y <= x  = y
  3857.  
  3858. Notice that this definition provides default definitions for all of the
  3859. member functions except (<=), so  that  in  general  only  this  single
  3860. function needs to be defined to construct an instance of class Ord.
  3861.  
  3862. There are two reasons for defining Eq as a superclass of Ord:
  3863.  
  3864.   o  The default definition for (<) relies on the  use  of  (/=)  taken
  3865.      from class Eq.  In order to guarantee that this is always valid we
  3866.      must ensure that every instance of Ord must also be an instance of
  3867.      Eq.
  3868.  
  3869.   o  Given the definition of a non-strict ordering (<=) on the elements
  3870.      of a type, it is always possible to construct a definition for the
  3871.      (==) operator (and hence for (/=)) using the equation:
  3872.  
  3873.                       x==y   =   x<=y && y<=x
  3874.  
  3875.      There will therefore be no loss in generality by requiring  Eq  to
  3876.      be a superclass of Ord, and conversely, no difficulty in  defining
  3877.      an instance of Eq to accompany any instance of  Ord  for  which an
  3878.      instance of Eq has not already be provided.
  3879.  
  3880.      As an example, the following definitions  provide  an  alternative
  3881.      way to implement the equality operation on  elements  of  the  Set
  3882.      datatype described in section  14.2.3,  in  terms  of  the  subset
  3883.      ordering defined in class Ord:
  3884.  
  3885.          instance Ord (Set a) => Eq (Set a) where
  3886.              x == y   =   x <= y  &&  y <= x
  3887.  
  3888.          instance Eq a => Ord (Set a) where
  3889.              Set xs <= Set ys  =  all (`elem` ys) xs
  3890.  
  3891.      This definition is in fact no less efficient or effective than the
  3892.      original version.
  3893.  
  3894. Dictionaries for superclasses are dealt with in much the  same  way  as
  3895. the instance specific dictionaries described above.  For  example,  the
  3896. general layout of a dictionary for an instance of Ord is illustrated in
  3897. the following diagram:
  3898.  
  3899.  +--------+--------+--------+--------+--------+--------+--------+-----
  3900.  |        |        |        |        |        |        |        |
  3901.  |  (<)   |  (<=)  |  (>)   |  (>=)  |  max   |  min   |  Eq a  | .....
  3902.  |        |        |        |        |        |        |        |
  3903.  +--------+--------+--------+--------+--------+--------+--------+-----
  3904.  
  3905. Note the use of the seventh element of this dictionary which points  to
  3906. the dictionary for the appropriate instance of Eq.  This is used in the
  3907. translation of the default definition for (<) which is equivalent to:
  3908.  
  3909.       defLessThan d x y  =  (<=) d x y  &&  (/=) (#7 d) x y
  3910.  
  3911.  
  3912. .ST 14.3.2 Combining classes
  3913. ------------------------
  3914. In general, a dictionary is made up of three separate parts:
  3915.  
  3916.      +-------------------+-------------------+-------------------+
  3917.      |  Implementation   |    Superclass     | Instance specific |
  3918.      | of class members  |   Dictionaries    |   Dictionaries    |
  3919.      |                   |                   |                   |
  3920.      +-------------------+-------------------+-------------------+
  3921.  
  3922. Each of these may be empty.  We have already  seen  examples  in  which
  3923. there are no superclass dictionaries (e.g.  instances  of  Eq)  and  in
  3924. which there are no  instance  specific  dictionaries  (e.g.   Eq  Int).
  3925. Classes with no member functions (corresponding to dictionaries with no
  3926. member functions) are sometimes useful as a convenient abbreviation for
  3927. a list of predicates.  For example:
  3928.  
  3929.     class  C a  where  cee :: a -> a
  3930.     class  D a  where  dee :: a -> a
  3931.  
  3932.     class  (C a, D a) => CandD a
  3933.  
  3934. makes CandD a an abbreviation for the context (C a, D a).  Thinking  of
  3935. single parameter type classes as sets of types, the  type  class  CandD
  3936. corresponds to the intersection of classes C and D.
  3937.  
  3938. Just as the type inferred  for  a  particular  function  definition  or
  3939. expression  does  not  involve  type  synonyms  unless  explicit   type
  3940. signatures are used, the Gofer  type  system  will  not  use  a  single
  3941. predicate of the form CandD a instead of the two predicates C a and D a
  3942. unless  explicit signatures are used:
  3943.  
  3944.     ? :t dee . cee
  3945.     \d129 d130 -> dee d130 . cee d129 :: (C a, D a) => a -> a
  3946.     ? :t dee . cee :: CandD a => a -> a
  3947.     \d129 -> dee (#2 d129) . cee (#1 d129) :: CandD a => a -> a
  3948.     ?
  3949.  
  3950. In Haskell,  all  instances  of  a  class  such  as  CandD  must   have
  3951. explicit declarations, in addition to  the  corresponding  declarations
  3952. for instances for C and D.  This problem can be avoided  by  using  the
  3953. more general form of instance declaration permitted in Gofer; a  single
  3954. instance declaration:
  3955.  
  3956.     instance CandD a
  3957.  
  3958. is all that is required to ensure that any instance  of  CandD  can  be
  3959. obtained, so long as corresponding instances for C and D can be found.
  3960.  
  3961.  
  3962. .ST 14.3.3 Simplified contexts
  3963. --------------------------
  3964. Consider the function defined by the following equation:
  3965.  
  3966.     eg1 x   =   [x] == [x]  ||  x == x
  3967.  
  3968. This definition does not restrict the type of x in any way except that,
  3969. if x :: a, then there must be instances Eq [a] and Eq a which are  used
  3970. for the two occurrences of the (==) operator in the equation.  We might
  3971. therefore expect the type of eg1 to be:
  3972.  
  3973.     (Eq [a], Eq a) => a -> Bool
  3974.  
  3975. with translation:
  3976.  
  3977.     eg1 d1 d2 x  =  (==) d1 [x] [x]  ||  (==) d2 x x
  3978.  
  3979. However, as can be seen  from  the  case  where  a=Int  illustrated  in
  3980. section 14.3, given d1::Eq [a] we can always find a dictionary for Eq a
  3981. by taking the third element of d1 i.e. (#3 d1)::Eq a.  Since it is more
  3982. efficient to select an element from a  dictionary  than  to  complicate
  3983. both type and translation with extra parameters, the type  assigned  to
  3984. "eg1" by default is:
  3985.  
  3986.     Eq [a] => a -> Bool
  3987.  
  3988. with translation:
  3989.  
  3990.     eg1 d1 x  =  (==) d1 [x] [x]  || (==) (#3 d1) x x
  3991.  
  3992. In general, given a set of predicates corresponding  to  the  instances
  3993. required by an expression,  Gofer  will  always  attempt  to  find  the
  3994. smallest possible subset of these  predicates  such  that  all  of  the
  3995. required dictionaries can still  be  obtained,  whilst  minimising  the
  3996. number of dictionary parameters that are used.
  3997.  
  3998. The original type and translation for eg1 given above can  be  produced
  3999. by including an explicit type signature  in  the  file  containing  the
  4000. definition of eg1:
  4001.  
  4002.     eg1   ::  (Eq [a], Eq a) => a -> Bool
  4003.     eg1 x  =  [x] == [x]  ||  x == x
  4004.  
  4005. But even with this definition, Gofer will still always try to  minimise
  4006. the number of dictionaries used in any particular expression:
  4007.  
  4008.     ? :t eg1
  4009.     \d153 -> eg1 d153 (#3 d153) :: Eq [a] => a -> Bool
  4010.     ?
  4011.  
  4012. As another example, consider the expression "(\x y->  x==x  ||  y==y)".
  4013. The type and translation assigned to this term can  be  found  directly
  4014. using Gofer:
  4015.  
  4016.     ? :t (\x y-> x==x || y==y)
  4017.     \d121 d122 x y -> (==) d122 x x ||
  4018.                       (==) d121 y y
  4019.                   :: (Eq b, Eq a) => a -> b -> Bool
  4020.     ?
  4021.  
  4022. Note that the translation has two dictionary parameters d121  and  d122
  4023. corresponding to the two predicates Eq a and Eq b respectively.   Since
  4024. both of these dictionaries can be obtained from a  dictionary  for  the
  4025. predicate Eq (a,b), we can use an explicit type signature to produce  a
  4026. translation which needs only one dictionary parameter:
  4027.  
  4028.     ? :t (\x y-> x==x || y==y) :: Eq (a,b) => a -> b -> Bool
  4029.     \d121 x y -> (==) (#3 d121) x x ||
  4030.                  (==) (#4 d121) y y
  4031.              :: Eq (a,b) => a -> b -> Bool
  4032.     ?
  4033.  
  4034.  
  4035. .cc 8
  4036. .ST 14.4 Other issues
  4037. -----------------
  4038.  
  4039. .ST 14.4.1 Unresolved overloading
  4040. -----------------------------
  4041. Consider  the  use  of  the  (==)  operator  in  the  following   three
  4042. situations:
  4043.  
  4044.   o  In the expression "2 == 3", it is clear that the appropriate value
  4045.      for the equality operator in this case is primIntEq as defined  by
  4046.      the instance declaration for Eq Int.  The expression can therefore
  4047.      be translated to "primEqInt 2 3".
  4048.  
  4049.   o  In the function definition "f x  =  x==x",  we  cannot  completely
  4050.      determine the appropriate value for (==) because it depends on the
  4051.      type assigned to the variable "x",  which  may  itself  vary  with
  4052.      different uses of the function "f".  It is however possible to add
  4053.      an extra parameter to the definition,  giving "f d x = (==) d x x"
  4054.      and taking the type of "f" to be Eq a => a -> Bool.
  4055.  
  4056.      In this way, the problem of finding the appropriate definition for
  4057.      the (==) operator is deferred until the function is actually used.
  4058.  
  4059.   o  In the expression "[]==[]", the appropriate value for (==) must be
  4060.      obtained from the dictionary for some instance of the form Eq [a],
  4061.      but there is not  sufficient  information  in  the  expression  to
  4062.      determine what the value of the type variable a should be.
  4063.  
  4064.      Looking back to the instance declaration for Eq [a], we find  that
  4065.      the definition of (==) depends on the value of the dictionary  for
  4066.      the instance Eq a.  In this particular case, it is clear that  the
  4067.      expression will always evaluate to True, regardless of  the  value
  4068.      of this dictionary.  Unfortunately, the only way that this can  be
  4069.      detected is by evaluating the expression to see if the calculation
  4070.      can be completed without reference to the  dictionary  value  (see
  4071.      the comments in the aside at the end of this section).
  4072.  
  4073.      Attempting to evaluate this expression  in  Gofer  will  therefore
  4074.      result in an error message indicating that the expression does not
  4075.      contain sufficient information to resolve the use  of  overloading
  4076.      in the expression:
  4077.  
  4078.          ? [] == []
  4079.          ERROR: Unresolved overloading
  4080.          *** type        : Eq [a] => Bool
  4081.          *** translation : \d129 -> (==) d129 [] []
  4082.          ?
  4083.  
  4084.      Note  that  the  expression  has  been  converted  into  a  lambda
  4085.      expression using the dictionary variable  d129  to  represent  the
  4086.      dictionary for the unknown instance Eq [a].
  4087.  
  4088.      One simple way to resolve the overloading in an expression of this
  4089.      kind is to use an explicit type signature.   For  example,  if  we
  4090.      specify that the second empty list is an empty list of type [Int]:
  4091.  
  4092.          ? [] == ([]::[Int])
  4093.          True
  4094.          (2 reductions, 9 cells)
  4095.          ?
  4096.  
  4097. The same problem occurs in Haskell, where it  is  described  using  the
  4098. idea of an `ambiguous type' -- i.e.  a  type  expression  of  the  form
  4099. context => type where one or more of the type  variables  appearing  in
  4100. the given context do not appear in  the  remaining  part  of  the  type
  4101. expression.
  4102.  
  4103. Further examples of unresolved overloading occur  with  other  classes.
  4104. As an example consider the class Reader defined by:
  4105.  
  4106.     class Reader a where 
  4107.         parse   :: String -> a   
  4108.         unparse :: a -> String
  4109.  
  4110. whose  member  functions  provide  methods  for  obtaining  the  string
  4111. representation of an element of an instance type,  and  for  converting
  4112. such representations  back  into  the  original values.  (The  standard
  4113. Haskell Text class  contains  similar  functions.)   Now  consider  the
  4114. expression "parse . unparse" which maps values from  some  instance  of
  4115. Reader to  values  of  another  instance  via  an  intermediate  string
  4116. representation.
  4117.  
  4118.     ? parse . unparse
  4119.     ERROR: Unresolved overloading
  4120.     *** type        : (Reader a, Reader b) => a -> b
  4121.     *** translation : \d129 d130 -> parse d130 . unparse d129
  4122.     ?
  4123.  
  4124. One of the first things that might surprise the reader here is that the
  4125. value produced by "parse . unparse" does not have to  be  of  the  same
  4126. type as the argument; for example, we would not usually expect to  have
  4127. any sensible interpretation for a floating point number  obtained  from
  4128. the string representation of a boolean value!
  4129.  
  4130. This can be fixed by using an explicit type declaration,  although  the
  4131. expression still produces unresolved overloading:
  4132.  
  4133.     ? (parse . unparse) :: Reader a => a -> a
  4134.     ERROR: Unresolved overloading
  4135.     *** type        : Reader a => a -> a
  4136.     *** translation : \d130 -> parse d130 . unparse d130
  4137.     ?
  4138.  
  4139. Notice however that the type of this expression  is  not  ambiguous  so
  4140. that the unresolved overloading in this example can be eliminated  when
  4141. the function is actually used:
  4142.  
  4143.     ? ((parse . unparse) :: Reader a => a -> a) 'a'
  4144.     'a'
  4145.     (4 reductions, 11 cells)
  4146.     ?
  4147.  
  4148. A more serious problem occurs with the  expression  "unparse  .  parse"
  4149. which maps string values to string values via some  intermediate  type.
  4150. Clearly this will lead to a problem with unresolved overloading:
  4151.  
  4152.     ? unparse . parse
  4153.     ERROR: Unresolved overloading
  4154.     *** type        : Reader a => String -> String
  4155.     *** translation : \d130 -> unparse d130 . parse (#0 d130)
  4156.     ?
  4157.  
  4158. Notice that the type obtained in  this  case  is  ambiguous;  the  type
  4159. variable a which appears in the predicate Reader a does not  appear  in
  4160. the type String -> String.  There are a number  of  ways  of  resolving
  4161. this kind of ambiguity:
  4162.  
  4163.   o  Using an explicitly typed expression: Assuming  for  example  that
  4164.      Char is an instance of Reader, we can write:
  4165.  
  4166.          ? unparse . (parse :: String -> Char)
  4167.          v113 {dict} . v112 {dict}
  4168.          (5 reductions, 42 cells)
  4169.          ?
  4170.  
  4171.      without any ambiguity.  If such type  signatures  are  used  in  a
  4172.      number of places, it  might  be  better  to  define  an  auxiliary
  4173.      function and use that instead:
  4174.  
  4175.          charParse :: String -> Char
  4176.          charParse  = parse
  4177.  
  4178.          ? unparse . charParse
  4179.          v113 {dict} . charParse
  4180.          (4 reductions, 37 cells)
  4181.          ?
  4182.  
  4183.      In such situations, it  is  perhaps  worth  asking  if  overloaded
  4184.      functions are in  fact  the  most  appropriate  solution  for  the
  4185.      problem at hand!
  4186.  
  4187.   o  Using an extra dummy parameter in a  function  definition.   In  a
  4188.      definition such as:
  4189.  
  4190.          f = unparse . parse
  4191.  
  4192.      we can introduce an additional dummy parameter `x'  which  is  not
  4193.      used except to determine the type of the result produced by  parse
  4194.      in f:
  4195.  
  4196.          f x  =  unparse . (parse `asTypeOf` (\""->x))
  4197.  
  4198.      where the standard prelude operator `asTypeOf` defined by:
  4199.  
  4200.          asTypeOf      :: a -> a -> a
  4201.          x `asTypeOf` _ = x
  4202.  
  4203.      is used to ensure that the type of parse in the definition of f is
  4204.      the same as that of the function (\""->x) -- in other  words,  the
  4205.      type must be String -> a where a is the type of the variable x.
  4206.  
  4207.      The resulting type for f is:
  4208.  
  4209.           f :: Reader a => a -> String -> String
  4210.  
  4211.      Notice how the addition of the dummy parameter has  been  used  to
  4212.      eliminate the ambiguity present in the original type.
  4213.  
  4214.      This kind of `coding trick' is rather messy and is not recommended
  4215.      for anything but the simplest examples.
  4216.  
  4217. [ASIDE: The idea of evaluating an expression with an ambiguous type  to
  4218. see if it does actually need the unspecified  dictionaries  could  have
  4219. been  implemented  quite easily in  Gofer  using  an  otherwise  unused
  4220. datatype Unresolved and generating instance declarations such as:
  4221.  
  4222.     instance Eq Unresolved where
  4223.         (==) = error "unresolved overloading for (==)"
  4224.         (/=) = error "unresolved overloading for (/=)"
  4225.  
  4226. for each class.  Given a particular expression, we  can  then  use  the
  4227. type Unused in place of any ambiguous type variables in its type.   The
  4228. evaluation of the expression could then be attempted, either completing
  4229. successfully if  the  dictionaries  are  not  required,  but  otherwise
  4230. resulting in a run-time error.
  4231.  
  4232. This approach is not used in Gofer; instead, the programmer is notified
  4233. of any unresolved  polymorphism  when  the  program  is  type  checked,
  4234. avoiding the possibility that a program  might  contain  an  undetected
  4235. ambiguity.]
  4236.  
  4237.  
  4238. .ST 14.4.2 `Recursive' dictionaries
  4239. -------------------------------
  4240. Unlike Haskell, there are no restrictions on the form of the predicates
  4241. that may appear in the context  part  of  a  Gofer  class  or  instance
  4242. declaration.  This has a  number  of  potentially  useful  applications
  4243. because it enables the  Gofer  programs  to  use  mutually  `recursive'
  4244. systems of dictionaries.
  4245.  
  4246. One example of this is the ability  to  implement  a  large  family  of
  4247. related functions using a group of classes instead of having to  use  a
  4248. single class.  The following example illustrates the technique with  an
  4249. alternative definition for the class Eq in  which  the  (==)  and  (/=)
  4250. operators are placed in different classes:
  4251.  
  4252.     class Neq a => Eq a  where  (==) :: a -> a -> Bool
  4253.  
  4254.     class Eq a => Neq a  where  (/=) :: a -> a -> Bool
  4255.                                 x/=y  = not (x == y)
  4256.  
  4257.  
  4258. [ASIDE: These declarations clash with those in the standard prelude and
  4259. hence cannot actually be used in Gofer unless a modified version of the
  4260. standard prelude is used instead.]
  4261.  
  4262. If we then give instance declarations:
  4263.  
  4264.     instance Eq Int  where (==) = primEqInt
  4265.     instance Neq Int
  4266.  
  4267. and try to evaluate the expression "2==3" then the following system  of
  4268. dictionaries will be generated:
  4269.  
  4270.         d1 :: Eq Int                   d2 :: Neq Int
  4271.         +-----------+-----------+      +-----------+-----------+
  4272.         |           |           |      |           |           |
  4273.     +-->| primEqInt |d2::Neq Int+----->| defNeq d2 |d1::Eq Int +---+
  4274.     |   |           |           |      |           |           |   |
  4275.     |   +-----------+-----------+      +-----------+-----------+   |
  4276.     |                                                              |
  4277.     +------------------------------<-------------------------------+
  4278.  
  4279. where the function "defNeq" is derived from the  default definition  in
  4280. the class Neq and is equivalent to:
  4281.  
  4282.                defNeq d x y  =  not ((==) (#2 d) x y)
  4283.  
  4284. Incidentally, if the instance declaration for Neq Int  above  had  been
  4285. replaced by:
  4286.  
  4287.     instance Neq a
  4288.  
  4289. then the effect of these declarations would be similar to the  standard
  4290. definition of the class Eq, except that it would  not  be  possible  to
  4291. override the  default  definition  for  (/=).   In  other  words,  this
  4292. approach would give the same effect as defining  (/=)  as  a  top-level
  4293. function rather than a member function in the class Eq:
  4294.  
  4295.     class Eq a  where  (==) :: a -> a -> Bool
  4296.  
  4297.     (/=)   ::  Eq a => a -> a -> Bool
  4298.     x /= y  =  not (x == y)
  4299.  
  4300. There are other situations in which recursive dictionaries of the  kind
  4301. described above can be  used.   A  further  example  is  given  in  the
  4302. following section.  Unfortunately, the lack of restrictions on the form
  4303. of class and instance declarations can also lead to  problems  in  some
  4304. (mostly pathological) cases.  As an example, consider the class:
  4305.  
  4306.     class Bad [a] => Bad a  where  bad :: a -> a
  4307.  
  4308. Without defining any instances of Bad, it is not possible to  construct
  4309. any dictionaries for instances of Bad:
  4310.  
  4311.     ? bad 2
  4312.     ERROR: Cannot derive instance in expression
  4313.     *** Expression        : bad d126 2
  4314.     *** Required instance : Bad Int
  4315.     ?
  4316.  
  4317. If however we add the instance declarations:
  4318.  
  4319.     instance Bad Int where bad = id
  4320.     instance Bad [a] where bad = id
  4321.  
  4322. then any attempt to construct  a  dictionary  for  Bad  Int  will  also
  4323. require a dictionary for the superclass Bad  [Int]  and  then  for  the
  4324. superclass of that instance Bad [[Int]] etc...  Since Gofer has only  a
  4325. finite amount of space for  storing  dictionaries,  this  process  will
  4326. eventually terminate when that space has been used up:
  4327.  
  4328.     ? bad 2
  4329.     ERROR: Dictionary storage space exhausted
  4330.     ?
  4331.  
  4332. [ASIDE: depending on the configuration of your  particular  version  of
  4333. Gofer and on the nature of the class and instance declarations that are
  4334. involved, an alternative error message "ERROR: Too many type  variables
  4335. in type checker" may be produced instead of the message shown above.]
  4336.  
  4337. From a practical point of view, this problem is unlikely to  cause  too
  4338. many real difficulties:
  4339.  
  4340.   o  Class declarations involving  predicates  such  as  those  in  the
  4341.      declaration of Bad are unlikely to be used in realistic programs.
  4342.  
  4343.   o  All dictionaries are constructed before evaluation  begins.   This
  4344.      process is guaranteed to terminate  because  each  new  dictionary
  4345.      that is created uses up part of  the  space  used  to  hold  Gofer
  4346.      dictionaries.  The  construction  process  will  either  terminate
  4347.      successfully once complete, or be aborted as soon as  all  of  the
  4348.      dictionary space has been used.
  4349.  
  4350. It remains to see what impact (if any) this has on realistic  programs,
  4351. and if later versions of  Gofer  should  be  modified  to  impose  some
  4352. syntactic restrictions (as in Haskell) or perhaps some form  of  static
  4353. checking of the contexts appearing in class and instance  declarations.
  4354.  
  4355.  
  4356. .ST 14.4.3 Classes with multiple parameters
  4357. ---------------------------------------
  4358. Gofer is the first language to support the use  of  type  classes  with
  4359. multiple parameters.  This again is  an  experimental  feature  of  the
  4360. language, intended to make it possible to explore  the  claims  from  a
  4361. number of researchers about the use of such classes.
  4362.  
  4363. Initial experiments suggest that multiple parameter  type  classes  are
  4364. likely  to  lead  to  large  numbers  of   problems   with   unresolved
  4365. overloading.  Ultimately, this may mean that such classes are  only  of
  4366. practical use in explicitly typed languages, or  alternatively  that  a
  4367. more powerful and general defaulting mechanism (similar to that used in
  4368. Haskell with numeric classes) is required to  support  user  controlled
  4369. overloading resolution.
  4370.  
  4371. The following declaration introduces a class  Iso  whose  elements  are
  4372. pairs of isomorphic types:
  4373.  
  4374.     class Iso b a => Iso a b  where  iso :: a -> b
  4375.  
  4376. The single member function "iso"  represents  the  isomorphism  mapping
  4377. elements of type a to corresponding  elements  of  type  b.   Note  the
  4378. `superclass' context in this declaration which formalises the idea that
  4379. if a is isomorphic to b then b is also isomorphic to a.  The class  Iso
  4380. therefore provides  further  examples  of  the  recursive  dictionaries
  4381. described in the previous section.
  4382.  
  4383. The fact that any type is isomorphic to itself can be described by the
  4384. following instance declaration:
  4385.  
  4386.     instance Iso a a where iso x = x
  4387.  
  4388. For example, the dictionary structure created in order to evaluate the
  4389. expression "iso 2 = 3" is:
  4390.  
  4391.                    d :: Iso Int Int
  4392.                    +--------------+--------------+
  4393.                    |              |              |
  4394.                +-->|      id      |d::Iso Int Int+--+
  4395.                |   |              |              |  |
  4396.                |   +--------------+--------------+  |
  4397.                |                                    |
  4398.                +------------------<-----------------+
  4399.  
  4400.     ? iso 2 == 3
  4401.     False
  4402.     (4 reductions, 11 cells)
  4403.     ? 
  4404.  
  4405. Our first taste of the problems to come occurs when we try to  evaluate
  4406. the expression "iso 2 == iso 3":
  4407.  
  4408.     ? iso 2 == iso 3
  4409.     ERROR: Unresolved overloading
  4410.     *** type        : (Eq a, Iso Int a) => Bool
  4411.     *** translation : \d130 d132 -> (==) d130 (iso d132 2) (iso d132 3)
  4412.     ?
  4413.  
  4414. In this case, the "iso" function is used to map the integers 2 and 3 to
  4415. elements of some type a, isomorphic to Int, and the values produced are
  4416. then compared using (==) at the instance Eq  a;  there  is  no  way  of
  4417. discovering what the value of a should be  without  using  an  explicit
  4418. type signature.
  4419.  
  4420. Further instances can be defined.  The following two  declarations  are
  4421. needed to describe the (approximate) isomorphism between lists of pairs
  4422. and pairs of lists:
  4423.  
  4424.     instance Iso [(a,b)] ([a],[b]) where  
  4425.         iso xs = (map fst xs, map snd xs)
  4426.  
  4427.     instance Iso ([a],[b]) [(a,b)] where
  4428.         iso (xs,ys) = zip xs ys
  4429.  
  4430. Unfortunately, even apparently straightforward examples  give  problems
  4431. with  unresolved  overloading,  forcing  the  use  of   explicit   type
  4432. declarations:
  4433.  
  4434.     ? iso [(1,2),(3,4)]
  4435.     ERROR: Unresolved overloading
  4436.     *** type        : Iso [(Int,Int)] a => a
  4437.     *** translation : \d126 -> iso d126 [(1,2),(3,4)]
  4438.  
  4439.     ? (iso [(1,2),(3,4)]) :: ([Int],[Int])
  4440.     ([1, 3],[2, 4])
  4441.     (22 reductions, 64 cells)
  4442.     ?
  4443.  
  4444. A second example of a multiple  parameter  type  class  is  defined  as
  4445. follows:
  4446.  
  4447.     class Ord a => Collects a b where
  4448.         emptyCollection :: b
  4449.         addToCollection :: a -> b -> b
  4450.         listCollection  :: b -> [a]
  4451.  
  4452. The basic intuition is that the predicate Collects a b  indicates  that
  4453. elements of type b can be used to represent collections of elements  of
  4454. type a.  A number of people have suggested using type classes  in  this
  4455. way to provide features similar to the (similarly named, but  otherwise
  4456. different) classes that occur in object-oriented languages.
  4457.  
  4458. Obvious implementations involve the use  of  ordered  lists  or  binary
  4459. search trees defined by instances of the form:
  4460.  
  4461.     data STree a = Empty | Node a (STree a) (STree a)
  4462.  
  4463.     instance Collects a [a] where ....
  4464.     instance Collects a (STree a) where ....
  4465.  
  4466. Once again, there are significant problems even  with  simple  examples
  4467. using these functions.  As an example, the standard way of  defining  a
  4468. function of type:
  4469.  
  4470.                   Collects a b => [a] -> b
  4471.  
  4472. mapping a list of values to a collection  of  those  values  using  the
  4473. higher order function "foldr":
  4474.  
  4475.     listToCollection = foldr addToCollection emptyCollection
  4476.  
  4477. actually produces a function with ambiguous type:
  4478.  
  4479.     ? :t foldr addToCollection emptyCollection
  4480.     \d139 d140 -> foldr (addToCollection d140) (emptyCollection d139)
  4481.               :: (Collects c b, Collects a b) => [a] -> b
  4482.     ?
  4483.  
  4484. which cannot be resolved, even with an explicit type declaration.
  4485.  
  4486.  
  4487. .ST 14.4.4 Overloading and numeric values
  4488. -------------------------------------
  4489. One of the most common uses of overloading is to allow the use  of  the
  4490. standard arithmetic operators such as (+), (*) etc. on the elements  of
  4491. a range of numeric types including integers and floating  point  values
  4492. in addition to user defined numeric types such as  arbitrary  precision
  4493. integers,  complex  and  rational  numbers,   vectors   and   matrices,
  4494. polynomials etc.  In Haskell, these features are supported by a  number
  4495. of built-in types and a complex hierarchy of  type  classes  describing
  4496. the operations defined on the elements of each numeric type.
  4497.  
  4498. As an experimental language, intended primarily for  the  investigation
  4499. of general purpose overloading, Gofer has  only  two  built-in  numeric
  4500. types; Int and Float (the second of  which  is  not  supported  in  all
  4501. implementations).  Similarly, although the Gofer system could  be  used
  4502. to  implement the  full  hierarchy  of  Haskell  numeric  classes,  the
  4503. standard prelude uses a single numeric type class Num defined by:
  4504.  
  4505.     class Eq a => Num a where           -- simplified numeric class
  4506.         (+), (-), (*), (/) :: a -> a -> a
  4507.         negate             :: a -> a
  4508.         fromInteger        :: Int -> a
  4509.  
  4510. The first four member functions (+), (-), (*),  (/)  are  the  standard
  4511. arithmetic functions on instances of Num, whilst "negate" denotes unary
  4512. negation.  The final member function, fromInteger is used to coerce any
  4513. integer value to the corresponding value in another  instance  of  Num.
  4514. An expression such as "fromInteger 3" is called an  overloaded  numeric
  4515. constant and has type Num a => a indicating that it can be  used  as  a
  4516. value of any instance of Num.  See below for examples.
  4517.  
  4518. Both Float and Int are defined as  instances  of  Num  using  primitive
  4519. functions for integer and floating point arithmetic:
  4520.  
  4521.     instance Num Int where
  4522.         (+)           = primPlusInt
  4523.         (-)           = primMinusInt
  4524.         (*)           = primMulInt
  4525.         (/)           = primDivInt
  4526.         negate        = primNegInt
  4527.         fromInteger x = x
  4528.  
  4529.     instance Num Float where
  4530.         (+)         = primPlusFloat
  4531.         (-)         = primMinusFloat
  4532.         (*)         = primMulFloat
  4533.         (/)         = primDivFloat 
  4534.         negate      = primNegFloat
  4535.         fromInteger = primIntToFloat
  4536.  
  4537. These definitions make it  possible  to  evaluate  numeric  expressions
  4538. involving both types:
  4539.  
  4540.     ? 2 + 3
  4541.     5
  4542.     (3 reductions, 6 cells)
  4543.     ? 3.2 + 4.321
  4544.     7.521
  4545.     (3 reductions, 13 cells)
  4546.     ?
  4547.  
  4548. Note  however  that  any  attempt  to  evaluate  an  expression  mixing
  4549. different arithmetic types is likely to cause a type error:
  4550.  
  4551.     ? 4.2 * 4
  4552.     ERROR: Type error in application
  4553.     *** expression     : 4.2 * 4
  4554.     *** term           : 4.2
  4555.     *** type           : Float
  4556.     *** does not match : Int
  4557.     ?
  4558.  
  4559. Further problems occur when we try to define functions intended  to  be
  4560. used with arbitrary instances  of  Num  rather  than  specific  numeric
  4561. types.  As an example of this, the  standard  prelude  function  "sum",
  4562. roughly equivalent to:
  4563.  
  4564.     sum []     = 0
  4565.     sum (x:xs) = x + sum xs
  4566.  
  4567. has type [Int] -> Int,  rather than the  more general Num a => [a] -> a
  4568. which could be used to find the sum of a list of numeric values in  any
  4569. instance of Num.  The problem in this particular case is caused by the
  4570. integer constant 0 in the first line of the definition.  Replacing this
  4571. with the expression fromInteger 0 leads to the following definition for
  4572. a generic sum function of the required type:
  4573.  
  4574.     genericSum       :: Num a => [a] -> a
  4575.     genericSum []     = fromInteger 0
  4576.     genericSum (x:xs) = x + genericSum xs
  4577.  
  4578. For example:
  4579.  
  4580.     ? genericSum [1,2,3]
  4581.     6
  4582.     (10 reductions, 18 cells)
  4583.     ? genericSum [1.0,2.0,3.0]
  4584.     6.0
  4585.     (11 reductions, 27 cells)
  4586.     ?
  4587.  
  4588. The fromInteger function  can  also  be  used  to  solve  the  previous
  4589. problem:
  4590.  
  4591.     ? 4.2 * fromInteger 4
  4592.     16.8
  4593.     (3 reductions, 13 cells)
  4594.     ?
  4595.  
  4596. In Haskell, any integer  constant  k  appearing  in  an  expression  is
  4597. treated as if the programmer had actually written  "fromInteger  k"  so
  4598. that  both  of  the  preceding  problems  are  automatically  resolved.
  4599. Unfortunately, this  also  creates  some  new  problems;  applying  the
  4600. function fromInteger to each integer constant in the previous  examples
  4601. causes problems with unresolved overloading:
  4602.  
  4603.     ? fromInteger 2 + fromInteger 3
  4604.     ERROR: Unresolved overloading
  4605.     *** type        : Num a => a
  4606.     *** translation : \d143 -> (+) d143 (fromInteger d143 2)
  4607.                                         (fromInteger d143 3)
  4608.     ?
  4609.  
  4610. Once again, Haskell provides a solution to this problem in the form  of
  4611. a `default mechanism' for  numeric  types  which,  once  the  following
  4612. problem has been detected, will typically `default'  the  unknown  type
  4613. represented by the type variable a above to be Int, so that the  result
  4614. is actually equivalent to the following:
  4615.  
  4616.     ? (fromInteger 2 + fromInteger 3) :: Int
  4617.     5
  4618.     (4 reductions, 8 cells)
  4619.     ?
  4620.  
  4621. There are a number of problems with the Haskell default mechanism; both
  4622. theoretical and practical.  In addition, if a default mechanism of some
  4623. form is used then it should also be capable of dealing  with  arbitrary
  4624. user-defined type classes, rather than  a  small  group  of  `standard'
  4625. classes, in order to provide solutions to  the  unresolved  overloading
  4626. problems described in  previous  sections.   Therefore,  for  the  time
  4627. being, Gofer does  not  support  any  form  of  default  mechanism  and
  4628. overloaded numeric constants can only be obtained by  explicit  use  of
  4629. the fromInteger function.
  4630.  
  4631.  
  4632. .ST 14.4.5 Constants in dictionaries
  4633. --------------------------------
  4634. The Gofer system constructs new dictionaries as necessary, and  deletes
  4635. them when they are no longer required.  At any one time,  there  is  at
  4636. most one dictionary for each instance of a class.   Coupled  with  lazy
  4637. evaluation, this has a number of advantages for classes in which member
  4638. functions are defined by variable declarations as in section 9.10.   As
  4639. an example, consider the class Finite defined by:
  4640.  
  4641.     class Finite a  where  members :: [a]
  4642.  
  4643. The only member in this class is a list enumerating the elements of the
  4644. type.  For example:
  4645.  
  4646.     instance Finite Bool  where  members = [False, True]
  4647.  
  4648.     instance (Finite a, Finite b) => Finite (a,b) where
  4649.         members = [ (x,y) | x<-members, y<-members ]
  4650.  
  4651. In order to overcome any problems with unresolved overloading, explicit
  4652. type signatures are often needed to resolve overloading:
  4653.  
  4654.     ? members :: [Bool]
  4655.     [False, True]
  4656.     (6 reductions, 26 cells)
  4657.     ? length (members :: [((Bool,Bool),(Bool,Bool))])
  4658.     16
  4659.     (103 reductions, 195 cells)
  4660.     ?
  4661.  
  4662. In some cases, the required overloading is implicit  from  the  context
  4663. and no additional type information is required,  as  in  the  following
  4664. example:
  4665.  
  4666.     ? [ x && y | (x,y) <- members ]
  4667.     [False, False, False, True]
  4668.     (29 reductions, 90 cells)
  4669.     ?
  4670.  
  4671. We can also use the technique of passing a `dummy' parameter to resolve
  4672. overloading problems in a function definition:
  4673.  
  4674.     size  :: Finite a => a -> Int
  4675.     size x = length (members `asTypeOf` [x])
  4676.  
  4677. which calculates the number of elements of  a  finite  type,  given  an
  4678. arbitrary element of that type:
  4679.  
  4680.     ? size (True,False)
  4681.     4
  4682.     (31 reductions, 60 cells)
  4683.     ?
  4684.  
  4685. Now consider the expression "size (True,False)  +  size  (True,False)".
  4686. At first glance, we expect  this  to  repeat  the  calculation  in  the
  4687. previous example two  times,  requiring  approximately  twice  as  many
  4688. reductions and cells as before.  However,  before  this  expression  is
  4689. evaluated, Gofer constructs a dictionary for Finite  (Bool,Bool).   The
  4690. evaluation of the first summand forces Gofer to evaluate the value  for
  4691. "members" in this dictionary.  Since precisely the same  dictionary  is
  4692. used to calculate the value of the second summand,  the  evaluation  of
  4693. "members" is not repeated and the complete  calculation  actually  uses
  4694. rather fewer reductions and cells:
  4695.  
  4696.     ? size (True,False) + size (True,False)
  4697.     8
  4698.     (51 reductions, 90 cells)
  4699.     ?
  4700.  
  4701. On the other hand, repeating the original calculation gives exactly the
  4702. same number of reductions and cells as before, because the dictionaries
  4703. constructed at the beginning of each calculation are not  retained  for
  4704. use in subsequent calculations.
  4705.  
  4706. We can force Gofer to construct specific  dictionaries  whilst  reading
  4707. from a file of definitions, so that they are not deleted at the end  of
  4708. each calculation, using an explicitly typed  variable  definition  such
  4709. as:
  4710.  
  4711.     boolBoolMembers = members :: [(Bool,Bool)]
  4712.  
  4713. This forces Gofer to construct the dictionary Finite (Bool,Bool)  when
  4714. the file of definitions is loaded and prevents it from being deleted at
  4715. the end of each calculation.  Having  loaded  a  file  containing  this
  4716. definition, the  first two  attempts  to  evaluate  "size (True,False)"
  4717. give:
  4718.  
  4719.     ? size (True,False)
  4720.     4
  4721.     (31 reductions, 60 cells)
  4722.     ? size (True,False)
  4723.     4
  4724.     (20 reductions, 32 cells)
  4725.     ?
  4726.  
  4727.  
  4728. .ST 14.4.6 The monomorphism restriction
  4729. -----------------------------------
  4730. This section  describes  a  technique  used  to  limit  the  amount  of
  4731. overloading used in the definition of certain values to avoid a  number
  4732. of technical problems.  This particular topic has attracted quite a lot
  4733. of attention within the Haskell community where  it  is  affectionately
  4734. known as the `dreaded monomorphism restriction'.  Although the  initial
  4735. formulation of the rule was rather cumbersome and limiting, the current
  4736. version used in both  Gofer  and  Haskell  is  unlikely  to  cause  any
  4737. problems in practice.  In  addition,  many  of  the  examples  used  to
  4738. motivate the need for the monomorphism restriction in Haskell occur  as
  4739. a result  of  the  use  of  implicitly  overloaded  numeric  constants,
  4740. described in section 14.4.4, and hence do not occur in Gofer.
  4741.  
  4742. The monomorphism restriction takes its name from the way  in  which  it
  4743. limits the amount of polymorphism that can be used in particular  kinds
  4744. of declaration.  Although we touch  on  this  point  in  the  following
  4745. discussion, the description given here uses  an  equivalent,  but  less
  4746. abstract approach, based on observations about  the  implementation  of
  4747. overloaded functions.
  4748.  
  4749. Basic ideas:
  4750. ------------
  4751. As we have seen,  the  implementation  of  overloading  used  by  Gofer
  4752. depends on being able to add extra arguments to a  function  definition
  4753. to supply the required dictionary parameters.   For  example,  given  a
  4754. function definition such as:
  4755.  
  4756.     isElement x []     =  False
  4757.     isElement x (y:ys) =  x==y || isElement x ys
  4758.  
  4759. we first add a dictionary parameter for the use of the overloaded  (==)
  4760. operator on the right hand side, obtaining:
  4761.  
  4762.     isElement x []     = False
  4763.     isElement x (y:ys) = (==) d x y || isElement x ys
  4764.  
  4765. Finally, we have to add the variable d  as  a  new  parameter  for  the
  4766. function isElement, on both the  left  and  right  hand  sides  of  the
  4767. definition:
  4768.  
  4769.     isElement d x []     = False
  4770.     isElement d x (y:ys) = (==) d x y || isElement d x ys
  4771.  
  4772. The monomorphism restriction imposes conditions which prevent this last
  4773. step from being used for certain kinds of value binding.
  4774.  
  4775. .cc 5
  4776. Declaration groups:
  4777. -------------------
  4778. Before giving the full details, it  is  worth  pointing  out  that,  in
  4779. general,  the  monomorphism  restriction  affects   groups   of   value
  4780. declarations rather than just individual  definitions.   To  illustrate
  4781. this point, consider the function definitions:
  4782.  
  4783.     f x y  =  x==y || g x y
  4784.     g x y  =  not (f x y)
  4785.  
  4786. Adding an appropriate dictionary parameter for the (==) operator gives:
  4787.  
  4788.     f x y  =  (==) d x y || g x y
  4789.     g x y  =  not (f x y)
  4790.  
  4791. The next stage is to  make  this  dictionary  variable  into  an  extra
  4792. parameter to the function f wherever it appears, giving:
  4793.  
  4794.     f d x y  =  (==) d x y || g x y
  4795.     g x y    =  not (f d x y)
  4796.  
  4797. But now the right hand side  of  the  second  definition  mentions  the
  4798. dictionary variable d  which  must  therefore  be  added  as  an  extra
  4799. parameter to g:
  4800.  
  4801.     f d x y  =  (==) d x y || g d x y
  4802.     g d x y  =  not (f d x y)
  4803.  
  4804. In other words, if dictionary parameters are added  to  any  particular
  4805. function  definition,  then  each  use  of  that  function  in  another
  4806. definition will also be require  extra  dictionary  parameters.   As  a
  4807. result, the monomorphism restriction has to be applied to the  smallest
  4808. groups of  declarations  such  that  any  pair  of  mutually  recursive
  4809. bindings are in the same group.
  4810.  
  4811. As the example above shows, if one (or more) of the bindings in a given
  4812. declaration group is affected by the monomorphism restriction  so  that
  4813. the appropriate dictionary parameters cannot be added as parameters for
  4814. that definition, then the same condition must also be imposed on all of
  4815. the other bindings in the group.  [Adding the extra parameter to  f  in
  4816. the example forces us to  add  an  extra  parameter  for  g;  if  extra
  4817. parameters were not permitted for g then they could not be added to f.]
  4818.  
  4819. .cc 5
  4820. Restricted bindings:
  4821. --------------------
  4822. There are three main reasons for avoiding adding dictionary  parameters
  4823. to a particular value binding:
  4824.  
  4825.   o  Dictionary parameters unnecessary.  If the dictionary  values  are
  4826.      completely determined by context then it is not necessary to  pass
  4827.      the appropriate values as dictionary parameters.  For example, the
  4828.      function definition:
  4829.  
  4830.          f x  =   x == 0  ||  x == 2
  4831.  
  4832.      can be translated as:
  4833.  
  4834.          f x  =   (==) {dict} x 0  ||  (==) {dict} x 2
  4835.  
  4836.      where, in both cases, the symbol {dict} denotes the dictionary for
  4837.      Eq Int.  As a further optimisation, once the dictionary  is  fully
  4838.      determined, this can be simplified to:
  4839.  
  4840.          f x  =   primEqInt x 0 || primEqInt x 2
  4841.  
  4842.   o  Dictionary parameters cannot be added in a pattern  binding.   One
  4843.      potential solution to this problem would be to replace the pattern
  4844.      binding by an equivalent set of function bindings.   In  practice,
  4845.      we do not use this technique because it typically causes ambiguity
  4846.      problems, as illustrated by the pattern binding:
  4847.  
  4848.          (plus,times) = ((+), (*))
  4849.  
  4850.      Translating this into a group of function bindings gives:
  4851.  
  4852.          newVariable  = ((+), (*))
  4853.          plus         = fst newVariable     -- fst (x,_) = x
  4854.          times        = snd newVariable     -- snd (_,y) = y
  4855.  
  4856.      The type of newVariable is (Num a, Num b) => (a->a->a, b->b->b) so
  4857.      that  the  correct  translation  of  these  bindings   using   two
  4858.      dictionary variables gives:
  4859.  
  4860.          newVariable da db = ((+) da, (*) db)
  4861.          plus da db        = fst (newVariable da db)
  4862.          times da db       = snd (newVariable da db)
  4863.  
  4864.      and hence the correct types for plus and times are:
  4865.  
  4866.          plus  :: (Num a, Num b) => a -> a -> a
  4867.          times :: (Num a, Num b) => b -> b -> b
  4868.      
  4869.      both of which are ambiguous.
  4870.  
  4871.   o  Adding dictionary parameters may translate a  variable  definition
  4872.      into  a  function  definition,  loosing  the  benefits  of  shared
  4873.      evaluation.  As an  example,  consider  the  following  definition
  4874.      using the function "size" and the class Finite  described  in  the
  4875.      previous section:
  4876.  
  4877.          twiceSize x = n + n  where n = size x
  4878.  
  4879.      Since the variable n is defined using a local definition, we would
  4880.      not expect to have to evaluate size x more than once to  determine
  4881.      the  value  of  twiceSize.   However,  adding   extra   dictionary
  4882.      parameters without restriction gives:
  4883.  
  4884.          twiceSize d x  = n d + n d  where  n d = size d x
  4885.  
  4886.      Now that n has been replaced by a function, the evaluation will be
  4887.      repeated, once for each occurrence of the expression  "n  d".   In
  4888.      order to avoid this kind of problem, the monomorphism  restriction
  4889.      does not usually allow extra parameters to be added to a  variable
  4890.      definition.  Thus the original definition above will be translated
  4891.      to give:
  4892.  
  4893.          twiceSize d x  =  n + n  where n = size d x
  4894.  
  4895.      Note that the same rule is applied to variable definitions at  the
  4896.      top-level of a file of definitions, resulting in an error  if  any
  4897.      dictionary parameters are required for the right hand side of  the
  4898.      definition.  As an example of this:
  4899.  
  4900.          twiceMembers = members ++ members
  4901.  
  4902.      which produces an error message of the form:
  4903.  
  4904.          ERROR "ex" (line 157): Unresolved top-level overloading
  4905.          *** Binding             : twiceMembers
  4906.          *** Inferred type       : [_7]
  4907.          *** Outstanding context : Finite _7
  4908.          ?
  4909.  
  4910.      [COMMENT: A type expression of the form _n (such  as  _7  in  this
  4911.      particular example) represents a  fixed  (i.e.  monomorphic)  type
  4912.      variable.]
  4913.  
  4914.      In  the  case  of  a  variable   declaration,   the   monomorphism
  4915.      restriction can be overcome by giving an explicit  type  signature
  4916.      including an appropriate context, to indicate  that  the  variable
  4917.      defined is intended to be used as an overloaded  value.   In  this
  4918.      case, we need only include the declaration:
  4919.  
  4920.          twiceMembers :: Finite a => [a]
  4921.  
  4922.      in the file containing the definition for twiceMembers to suppress
  4923.      the previous error message and allow the function to be used as  a
  4924.      fully overloaded variable.
  4925.  
  4926.      Note that the monomorphism restriction interferes with the use  of
  4927.      polymorphism.  For example, the definition:
  4928.  
  4929.          aNumber = length (twiceMembers::[Bool]) +
  4930.                    length (twiceMembers::[(Bool,Bool)])
  4931.                    where twiceMembers = members ++ members
  4932.  
  4933.      will not be accepted because the monomorphism  restriction  forces
  4934.      the local definition of  "twiceMembers"  to  be  restricted  to  a
  4935.      single overloading (the dictionary parameter supplied to each  use
  4936.      of members must be constant throughout the local definition):
  4937.  
  4938.          ERROR "ex" (line 12): Type error in type signature expression
  4939.          *** term           : twiceMembers
  4940.          *** type           : [(Bool,Bool)]
  4941.          *** does not match : [Bool]
  4942.          ?
  4943.  
  4944.      Once again, this problem can  be  fixed  using  an  explicit  type
  4945.      declaration:
  4946.  
  4947.          aNumber = length (twiceMembers::[Bool]) +
  4948.                    length (twiceMembers::[(Bool,Bool)])  
  4949.                    where twiceMembers :: Finite a => [a]
  4950.                          twiceMembers  = members ++ members
  4951.  
  4952.  
  4953. Formal definition:
  4954. ------------------
  4955. The  examples  above  describe  the  motivation  for  the  monomorphism
  4956. restriction, captured by the following definition:
  4957.  
  4958. Dictionary variables will not  be  used  as  extra  parameters  in  the
  4959. definition of a value in a given declaration group G if:
  4960.  
  4961.    either:  G includes a pattern binding
  4962.  
  4963.        or:  G includes a variable declaration, but does not include  an
  4964.             explicit type signature for any of  the  variables  in  the
  4965.             group.
  4966.  
  4967. If neither of these conditions hold, then equivalent sets of dictionary
  4968. parameters will be added to each declaration in the group.
  4969.  
  4970. .pa
  4971. .>appx_a
  4972. .ST APPENDIX A: SUMMARY OF GRAMMAR
  4973.  
  4974. This section gives a summary of the grammar for the  language  used  by
  4975. Gofer.  The non-terminals <interp> and <module> describe the syntax  of
  4976. expressions that can be entered into the Gofer interpreter and that  of
  4977. files of definitions that can be loaded into Gofer respectively.
  4978.  
  4979. The following notational conventions are used in the Grammar  which  is
  4980. specified using a variant of BNF:
  4981.  
  4982.   o <angle brackets> are used to distinguish names of nonterminals from
  4983.     keywords.
  4984.  
  4985.   o vertical | bars  are used to separate alternatives.
  4986.  
  4987.   o {braces} enclose items which may be repeated zero or more times.
  4988.  
  4989.   o [brackets] are used for optional items.
  4990.  
  4991.   o (parentheses) are used for grouping.
  4992.  
  4993.   o "quotes" surround characters which might otherwise be confused with
  4994.     the notations introduced above.
  4995.  
  4996. The following terminal symbols are used but not defined by the grammar:
  4997.  
  4998.   VARID    identifier beginning with lower case letter as described in
  4999.            section 6.
  5000.   CONID    like VARID, but beginning with upper case letter.
  5001.   VAROP    operator symbol not beginning with a colon, as described in
  5002.            section 6.
  5003.   CONOP    constructor function operator, like VAROP, but beginning
  5004.            with a colon character.
  5005.   INTEGER  integer constant, as described in section 7.3.
  5006.   FLOAT    floating point constant, as described in section 7.4.
  5007.   CHAR     character constant, as described in section 7.5.
  5008.   STRING   string constant, as described in section 7.7.
  5009.  
  5010.  
  5011. Top-level grammar
  5012. -----------------
  5013.  
  5014.     <module>   ::= "{" <topdecls> "}"               module
  5015.  
  5016.     <interp>   ::= <exp> [<where>]                  top-level expression
  5017.  
  5018.     <topdecls> ::= <topdecls>; <topdecls>           multiple declarations
  5019.                 |  data <typeLhs> = <constrs>       datatype declaration
  5020.                 |  type <typeLhs> = <type>          synonym declaration
  5021.                 |  infixl [<digit>] <op> {, <op>}   fixity declarations
  5022.                 |  infixr [<digit>] <op> {, <op>}
  5023.                 |  infix  [<digit>] <op> {, <op>}
  5024.                 |  primitive <prims> :: <type>      primitive bindings
  5025.                 |  <class>                          class declaration
  5026.                 |  <inst>                           instance declaration
  5027.                 |  <decls>                          value declarations
  5028.  
  5029.     <typeLhs>  ::= CONID {VARID}                    type declaration lhs
  5030.  
  5031.     <constrs>  ::= <constrs> "|" <constrs>          multiple constructors
  5032.                 |  <type> CONOP <type>              infix constructor
  5033.                 |  CONID {<type>}                   constructor, n>=0
  5034.  
  5035.     <prims>    ::= <prims>, <prims>                 multiple bindings
  5036.                 |  <var> <string>                   primitive binding
  5037.  
  5038. Type expressions
  5039. ----------------
  5040.  
  5041.     <sigType>  ::= [<context> => ] <type>           [qualified] type
  5042.  
  5043.     <context>  ::= "(" [<pred> {, <pred>}] ")"      general form
  5044.                 |  <pred>                           singleton context
  5045.     <pred>     ::= CONID <type> {<type>}            predicate
  5046.  
  5047.     <type>     ::= <ctype> [ -> <type> ]            function type
  5048.     <ctype>    ::= CONID {<atype>}                  datatype or synonym
  5049.                 |  <atype>
  5050.     <atype>    ::= VARID                            type variable
  5051.                 |  "(" ")"                          unit type
  5052.                 |  "(" <type> ")"                   parenthesised type
  5053.                 |  "(" <type>,<type> {,<type>} ")"  tuple type
  5054.                 |  "[" <type> "]"                   list type
  5055.  
  5056. Class and instance declarations
  5057. -------------------------------
  5058.  
  5059.     <class>    ::= class [<context> =>] <pred> [<cbody>]
  5060.     <cbody>    ::= where "{" <cdecls> "}"           class body
  5061.     <cdecls>   ::= <cdecls>; <cdecls>               multiple declarations
  5062.                 |  <var> {, <var>} :: <type>        member functions
  5063.                 |  <fun> <rhs> [<where>]            default bindings
  5064.  
  5065.     <inst>     ::= instance [<context> =>] <pred> [<ibody>]
  5066.     <ibody>    ::= where "{" <idecls> "}"           instance body
  5067.     <idecls>   ::= <idecls>; <idecls>               multiple declarations
  5068.                 |  <fun> <rhs> [<where>]            member definition
  5069.  
  5070. Value declarations
  5071. ------------------
  5072.  
  5073.     <decls>  ::= <decls>; <decls>                 multiple declarations
  5074.               |  <var> {, <var>} :: <sigType>     type declaration
  5075.               |  <fun> <rhs> [<where>]            function binding
  5076.               |  <pat> <rhs> [<where>]            pattern binding
  5077.  
  5078.     <rhs>    ::= = <exp>                          simple right hand side
  5079.               |  <gdRhs> {<gdRhs>}                guarded right hand sides
  5080.  
  5081.     <gdRhs>  ::= "|" <exp> = <exp>                guarded right hand side
  5082.  
  5083.     <where>  ::= where "{" <decls> "}"            local definitions
  5084.  
  5085.     <fun>    ::= <var>                            function of arity 0
  5086.               |  <pat> <varop> <pat>              infix operator
  5087.               |  "(" <pat> <varop> ")"            section-like notation
  5088.               |  "(" <varop> <pat> ")"
  5089.               |  <fun> <apat>                     function with argument
  5090.               |  "(" <fun> ")"                    parenthesised lhs
  5091.  
  5092. Expressions
  5093. -----------
  5094.  
  5095.     <exp>    ::= \ <apat> {<apat>} -> <exp>       lambda expression
  5096.               |  let "{" <decls> "}" in <exp>     local definition
  5097.               |  if <exp> then <exp> else <exp>   conditional expression
  5098.               |  case <exp> of "{" <alts> "}"     case expression
  5099.               |  <opExp> :: <sigType>             typed expression
  5100.               |  <opExp>
  5101.     <opExp>  ::= <opExp> <op> <opExp>             operator application
  5102.               |  <pfxExp>
  5103.     <pfxExp> ::= - <appExp>                       negation
  5104.               |  <appExp>
  5105.     <appExp> ::= <appExp> <atomic>                function application
  5106.               |  <atomic>
  5107.     <atomic> ::= <var>                            variable
  5108.               |  <conid>                          constructor
  5109.               |  INTEGER                          integer literal
  5110.               |  FLOAT                            floating point literal
  5111.               |  CHAR                             character literal
  5112.               |  STRING                           string literal
  5113.               |  "(" ")"                          unit element
  5114.               |  "(" <exp> ")"                    parenthesised expr.
  5115.               |  (<exp> <op>)                     sections
  5116.               |  (<op> <exp>)
  5117.               |  "[" <list> "]"                   list expression
  5118.               |  "(" <exp>, <exp> {, <exp>} ")"   tuple
  5119.  
  5120.     <list>   ::= [ <exp> {, <exp>} ]              enumerated list
  5121.               |  <exp> "|" <quals>                list comprehension
  5122.               |  <exp> ..                         arithmetic sequence
  5123.               |  <exp>, <exp> ..
  5124.               |  <exp> .. <exp>
  5125.               |  <exp>, <exp> .. <exp>
  5126.     <quals>  ::= <quals>, <quals>                 multiple qualifiers
  5127.               |  <pat> <- <exp>                   generator
  5128.               |  <pat> = <exp>                    local definition
  5129.               |  <exp>                            boolean guard
  5130.  
  5131.     <alts>   ::= <alts>; <alts>                   multiple alternatives
  5132.               |  <pat> <altRhs> [<where>]         alternative
  5133.     <altRhs> ::= -> <exp>                         single alternative
  5134.               |  <gdAlt> {<gdAlt>}                guarded alternatives
  5135.     <gdAlt>  ::= "|" <exp> -> <exp>               guarded alternative
  5136.  
  5137. Patterns
  5138. --------
  5139.  
  5140.     <pat>    ::= <pat> <conop> <pat>              operator application
  5141.               |  <var> + <integer>                (n+k) pattern
  5142.               |  <appPat>
  5143.     <appPat> ::= <appPat> <apat>                  application
  5144.               |  <apat>
  5145.     <apat>   ::= <var>                            variable
  5146.               |  <var> @ <pat>                    as pattern
  5147.               |  ~ <pat>                          irrefutable pattern
  5148.               |  _                                wildcard
  5149.               |  <conid>                          constructor
  5150.               |  INTEGER                          integer literal
  5151.               |  CHAR                             character literal
  5152.               |  STRING                           string literal
  5153.               |  "(" ")"                          unit element
  5154.               |  "(" <pat> ")"                    parenthesised expr.
  5155.               |  (<pat> <conop>)                  sections
  5156.               |  (<conop> <pat>)
  5157.               |  "[" [ <pat> {, <pat>} ] "]"      list
  5158.               |  "(" <pat>, <pat> {, <pat>} ")"   tuple
  5159.  
  5160. Variables and operators
  5161. -----------------------
  5162.  
  5163.     <var>    ::= <varid>  |  "(" - ")"            variable
  5164.     <op>     ::= <varop>  |  <conop>   |  -       operator
  5165.  
  5166.     <varid>  ::= VARID    |  "(" VAROP ")"        variable identifier
  5167.     <varop>  ::= VAROP    |  ` VARID `            variable operator
  5168.  
  5169.     <conid>  ::= CONID    |  "(" CONOP ")"        constructor identifier
  5170.     <conop>  ::= CONOP    |  ` CONID `            constructor operator
  5171.  
  5172. .pa
  5173. .>appx_b
  5174. .ST APPENDIX B: CONTENTS OF STANDARD PRELUDE
  5175.  
  5176. .in ../standard.prelude
  5177. .pa
  5178. .>appx_c
  5179. .ST APPENDIX C: RELATIONSHIP WITH HASKELL 1.1
  5180.  
  5181. The language supported by Gofer is both syntactically and  semantically
  5182. similar to that of  the  functional  programming  language  Haskell  as
  5183. defined in the report  for  Haskell  version  1.1  [5].   This  section
  5184. details the differences between the two languages, outlined briefly  in
  5185. section 2.
  5186.  
  5187. .cc 5
  5188. Haskell features not included in Gofer:
  5189. ---------------------------------------
  5190.   o  Modules
  5191.  
  5192.   o  Arrays
  5193.  
  5194.   o  Derived instances for standard classes -- the ability to construct
  5195.      instances of particular classes automatically.
  5196.  
  5197.   o  Default mechanism for eliminating unresolved overloading involving
  5198.      numeric and standard classes.   Since  Gofer  is  an  experimental
  5199.      system, it can be  used  with  a  range  of  completely  different
  5200.      prelude files; there is no concept of `standard classes'.
  5201.  
  5202.   o  Overloaded numeric constants.  In  the  absence  of  a  defaulting
  5203.      mechanism  as  mentioned  in  the  previous  item,  problems  with
  5204.      unresolved overloading make implicitly typed programming involving
  5205.      numeric constants impractical in an interpreter based system.
  5206.  
  5207.   o  Full range of numeric types  and  classes.   Gofer  has  only  two
  5208.      primitive numeric types Int and Float (the second of which is  not
  5209.      supported in the PC version).  Although is would  be  possible  to
  5210.      modify the standard prelude so that  Gofer  uses  the  same  class
  5211.      hierarchy as Haskell, this is unnecessarily sophisticated for  the
  5212.      intended uses of Gofer.
  5213.  
  5214.   o  Datatype definitions in Haskell may involve class constraints such
  5215.      as:
  5216.  
  5217.               data  Ord a => Set a = Set [a]
  5218.  
  5219.      It is  not  clear  how  such  constraints  should  be  interpreted
  5220.      (particularly in the light of the  extended  form  of  constraints
  5221.      used by Gofer) in such a way to  make  them useful whilst avoiding
  5222.      unwanted ambiguity problems.
  5223.  
  5224.  
  5225. .cc 5
  5226. Gofer features not supported in Haskell:
  5227. ----------------------------------------
  5228.   o  Type classes may have multiple parameters.
  5229.  
  5230.   o  Predicates  in  type  expressions  may  involve   arbitrary   type
  5231.      expressions, not just type variables as used in Haskell.
  5232.  
  5233.   o  Instances of type classes can be defined at  non-overlapping,  but
  5234.      otherwise arbitrary types, as described in section 14.2.5.
  5235.  
  5236.   o  List comprehensions  may include  local definitions,  specified by
  5237.      qualifiers of the form <pat>=<expr> as described in section 10.2.
  5238.  
  5239.   o  No restrictions are placed on the form of predicates  that  appear
  5240.      in the context for a class or instance declaration.   This  has  a
  5241.      number  of  consequences,  including  the  possibility  of   using
  5242.      (mutually)  recursive  groups  of  dictionaries,  but  means  that
  5243.      decidability of the predicate entailment  relation  may  be  lost.
  5244.      This is not a great problem  in  practice,  since  all  dictionary
  5245.      construction  is  performed  before  evaluation   and   supposedly
  5246.      non-terminating dictionary constructions will actually generate an
  5247.      error due to the limited amount of  space  available  for  holding
  5248.      dictionaries (see section 14.4.2).
  5249.  
  5250.  
  5251. .cc 5
  5252. Other differences:
  5253. ------------------
  5254.   o  Whilst superficially similar the approach to type classes in Gofer
  5255.      is quite different from that used in Haskell.  In particular,  the
  5256.      approach used in Gofer ensures that all necessary dictionaries are
  5257.      constructed before the evaluation of an expression begins,  rather
  5258.      than being built (possibly several times) during the evaluation as
  5259.      is the case with Haskell.  See section 14 and reference  [11]  for
  5260.      further details.
  5261.  
  5262.   o  Input/Output facilities - Gofer supports  only  a  subset  of  the
  5263.      requests available in Haskell.  In principle, it should not be too
  5264.      difficult to add most of the remaining forms of request (with  the
  5265.      exception of those associated with binary files)  to  Gofer.   The
  5266.      principal motivation for including the I/O facilities in Gofer was
  5267.      to  make  it  possible  to  experiment  with  simple   interactive
  5268.      programs.
  5269.  
  5270.   o  In Gofer, unary minus has greater  precedence  than  any  operator
  5271.      symbol, but lower than that of function application.  In  Haskell,
  5272.      the precedence of unary minus is the same as  that  of  the  infix
  5273.      (subtraction) operator of the same name.
  5274.  
  5275.   o  In Haskell, the character `-'  can  only  be  used  as  the  first
  5276.      character of an operator symbol.  In  Gofer,  this  character  may
  5277.      appear  in  any  position  in  an  operator  (except  for  symbols
  5278.      beginning with "--", which indicates the start of a comment).  The
  5279.      only problems that I am aware  of  with  this  is  that  a  lambda
  5280.      expression such as "\-2->2" will be parsed as such  by  a  Haskell
  5281.      system, but cause a syntax error in Gofer.  This  form  of  lambda
  5282.      expression is sufficiently unusual that I do not believe this will
  5283.      cause any problems in practice; in any case, the  parsing  problem
  5284.      can be solved by inserting a space: "\ -2->2".
  5285.  
  5286.   o  Pattern bindings are not currently permitted in either instance or
  5287.      class declarations.  This restriction has  been  made  simply  for
  5288.      ease of implementation, is not an inherent problem with  the  type
  5289.      class system and is likely to be  relaxed  in  later  versions  of
  5290.      Gofer if appropriate.  I have yet to see any examples in which the
  5291.      lack of pattern bindings in class and instance declarations causes
  5292.      any kind of deficiency.
  5293.  
  5294.   o  Qualified  type  signatures  are  not  permitted  for  the  member
  5295.      functions  in  Gofer  class  declarations.    Once   again,   this
  5296.      restriction was made for ease of implementation  rather  than  any
  5297.      pressing technical issues.  It is  likely  that  this  restriction
  5298.      will be relaxed in future versions of Gofer,  although  I  am  not
  5299.      convinced that proper use can be made  of  such  member  functions
  5300.      without some form of nested instance declarations (yuk!).
  5301.  
  5302.   o  The definition of the class Text given  in  the  standard  prelude
  5303.      does not include the Haskell functions for reading/parsing  values
  5304.      from strings; the only reason for omitting these functions was  to
  5305.      try to avoid unnecessary complexity in the standard prelude.   The
  5306.      standard prelude  can  be  modified  to  include  the  appropriate
  5307.      additional definitions if these are required.
  5308.  
  5309.  
  5310. .cc 5
  5311. Known problems in Gofer:
  5312. ------------------------
  5313.   o  The null escape sequence "\&" is not generated  in  the  printable
  5314.      representations of strings produced by both the primitive function
  5315.      primPrint (used to implement the show' function) and  the  version
  5316.      of show defined in the standard prelude.  This means that  certain
  5317.      strings values are  not printed correctly  e.g.  show' "\245\&123"
  5318.      produces the string "\245123".  This is unlikely to cause too many
  5319.      problems in practice.
  5320.  
  5321.   o  Unification of a type variable a with a  type  expression  of  the
  5322.      form T a where T is  a  synonym  name  whose  expansion  does  not
  5323.      involve a will fail.   It  is  not  entirely  clear  whether  this
  5324.      behaviour is correct or not.
  5325.  
  5326.   o  Formfeeds '\f' and vertical tabs '\v' are  not  treated  as  valid
  5327.      whitespace characters in the way suggested by the Haskell  report.
  5328.  
  5329.   o  Inability to recover from program stack  overlow  errors  in  some
  5330.      situations.  This problem only affects the  PC  implementation  of
  5331.      Gofer.
  5332.  
  5333.   o  Implementation of ReadFile may lose referential transparency;  the
  5334.      response to a particular ReadFile request may  be  affected  by  a
  5335.      later WriteFile or AppendFile request for the same  file.   Whilst
  5336.      this problem can be solved for UNIX based implementations, I  have
  5337.      not yet found a portable solution suitable for all of the  systems
  5338.      on which Gofer can be used.
  5339.  
  5340.  
  5341. .cc 5
  5342. Areas for possible future improvement:
  5343. --------------------------------------
  5344.   o  Relaxing the restriction on type synonyms in predicates.
  5345.  
  5346.   o  General  purpose  automatic  default  mechanism  for   eliminating
  5347.      certain forms of unresolved overloading.
  5348.  
  5349.   o  Improved checking and use of superclass and  instance  constraints
  5350.      during static analysis and type checking.
  5351.  
  5352.   o  Simple facility to force dictionary construction at load-time.
  5353.  
  5354.   o  Provision for shell escapes :! etc within the Gofer interpreter.
  5355.  
  5356.   o  Debugging  facilities,  including  breakpoints  and  tracing  from
  5357.      within interpreter.
  5358.  
  5359.   o  Separate interpreter and compiler programs for creating standalone
  5360.      applications using Gofer.
  5361. .pa
  5362. .>appx_d
  5363. .ST APPENDIX D: USING GOFER WITH BIRD+WADLER
  5364.  
  5365. Bird and Wadler's textbook  [1]  gives  an  excellent  introduction  to
  5366. functional programming, providing an insight into both basic techniques
  5367. and matters of programming style as well as describing  the  underlying
  5368. mathematics and its use for program development and  derivation.   Most
  5369. of the programs in that book can be used with Gofer although there  are
  5370. a number of differences between the two notations.  Fortunately, it  is
  5371. not difficult to  translate  from  one  notation  to  the  other.   The
  5372. following points are particularly useful for this:
  5373.  
  5374.   o  Type constructors in Gofer  begin with capital letters (e.g. Bool,
  5375.      Char etc..) where lower case is used in  [1]  (e.g.   bool,  char,
  5376.      etc..).  Note that Gofer has no general numeric type "num" as used
  5377.      in [1];  Use  either  Int,  Float,  or  overloading  in  Gofer  as
  5378.      appropriate.
  5379.  
  5380.   o  Datatype definitions in [1] are written in the form lhs::=constrs.
  5381.      The equivalent definition in Gofer is: data lhs = constrs.
  5382.  
  5383.      Similarly, a type synonym definition in [1] of the form lhs == rhs
  5384.      can be written in Gofer as: type lhs = rhs.
  5385.  
  5386.   o  The differences between the syntax used for  guarded equations  in
  5387.      Gofer compared with the notation used in  [1]  have  already  been
  5388.      discussed in section 9.2.  For example:
  5389.  
  5390.      Using the notation of [1]:       Using Gofer:
  5391.  
  5392.      filter p (x:xs)                  filter p (x:xs)
  5393.        = x : filter p xs, if p x         | p x       = x : filter p xs
  5394.        = filter p xs,     otherwise      | otherwise = filter p xs
  5395.  
  5396.   o  In Gofer,  list comprehension qualifiers  are separated by  commas
  5397.      rather than semicolons as used in [1].
  5398.  
  5399.   o  A number of the  function names and types in the  standard prelude
  5400.      are different:
  5401.  
  5402.              [1]         Gofer            [1]         Gofer
  5403.              ---         -----            ---         ----
  5404.              (#)         length           takewhile   takeWhile
  5405.              (~)         not              dropwhile   dropWhile
  5406.              (/\)        (&&)             zipwith     zipWith
  5407.              (\/)        (||)             swap        flip
  5408.              (!)         (!!)             in          elem
  5409.              (--)        (\\)             scan        scanl
  5410.              hd          head             some        any
  5411.              tl          tail             listmin     minimum
  5412.              decode      chr              listmax     maximum
  5413.              code        ord
  5414.  
  5415.      See appendix B for a complete list of standard functions in Gofer.
  5416.  
  5417.      The version of foldl  using  "strict"  which  appears  in  [1]  is
  5418.      available in Gofer as the function "foldl'".
  5419.  
  5420.      The role of "zip" and "zipwith" in [1] is filled by the "zip"  and
  5421.      "zipWith" families of functions in Gofer.  An  expression  of  the
  5422.      form "zip (xs,ys)" in [1] is equivalent to "zip xs  ys"  in  Gofer
  5423.      etc...
  5424.  
  5425.   o  Gofer does not enforce the condition assumed in [1] that the  left
  5426.      hand sides of each of the equations defining a  function  must  be
  5427.      disjoint.
  5428.  
  5429.   o  The equality operator in Gofer is written as  "=="  and the single
  5430.      equality character "=" is a reserved symbol used to separate  left
  5431.      and right hand sides of equations.  Many  C  programmers  will  be
  5432.      familiar with this kind of notation (together with  the  kinds  of
  5433.      problems it can create!).
  5434.  
  5435.   o  Some of the  identifiers used in  [1] are reserved words in Gofer.
  5436.      Examples that are particularly likely to occur  include  "in"  and
  5437.      "then".
  5438. .pa
  5439. .>appx_e
  5440. .ST APPENDIX E: PRIMITIVES
  5441.  
  5442. [WARNING: The features described in this appendix  are  typically  only
  5443. needed when alternative versions of the standard prelude  are  created.
  5444. These features should only be used by expert users; misuse may lead  to
  5445. failure and runtime errors in the Gofer interpreter.  It is not usually
  5446. a good idea to use primitive functions directly in your programs.]
  5447.  
  5448. A number of primitive functions are builtin to the  Gofer  interpreter,
  5449. and may be bound to function symbols using a declaration of the form:
  5450.  
  5451.     primitive name1 code1, name2 code2, ...., namen coden :: type
  5452.  
  5453. where each name is an identifier (or an  operator  symbol  enclosed  by
  5454. parentheses) and each code is a string literal  taken  from  the  table
  5455. below.  The type specified to the right of the  ::  symbol  must  be  a
  5456. valid type for the functions being defined -- WARNING: GOFER  DOES  NOT
  5457. ATTEMPT TO CHECK FOR SUITABILITY OF THE DECLARED TYPE.   The  following
  5458. definition, taken from the standard prelude,  illustrates  the  use  of
  5459. this feature to bind  a  function  named  primPrint  to  the  primitive
  5460. function with code name string "primPrint" and type Int -> a ->  String
  5461. -> String:
  5462.  
  5463.     primitive primPrint "primPrint"  :: Int -> a -> String -> String
  5464.  
  5465. The primitive functions currently available are:
  5466.  
  5467. category     code name string    type
  5468. --------     ----------------    ----
  5469.  
  5470. integer      primPlusInt         Int -> Int -> Int 
  5471. arithmetic   primMinusInt        Int -> Int -> Int
  5472.              primMulInt          Int -> Int -> Int
  5473.              primDivInt          Int -> Int -> Int
  5474.              primModInt          Int -> Int -> Int
  5475.              primRemInt          Int -> Int -> Int
  5476.              primNegInt          Int -> Int -> Int
  5477.  
  5478.  
  5479. floating     primPlusFloat       Float -> Float -> Float
  5480. point        primMinusFloat      Float -> Float -> Float
  5481. arithmetic   primMulFloat        Float -> Float -> Float
  5482.              primDivFloat        Float -> Float -> Float
  5483.              primNegFloat        Float -> Float -> Float
  5484.  
  5485.  
  5486. coercion     primIntToChar       Int -> Char  -- chr in the standard prelude
  5487. functions    primCharToInt       Char -> Int  -- ord in the standard prelude
  5488.              primIntToFloat      Int -> Float -- implements fromInteger
  5489.  
  5490. equality     primEqInt           Int -> Int -> Bool
  5491. and <=       primLeInt           Int -> Int -> Bool
  5492. primitives   primEqFloat         Float -> Float -> Bool
  5493.              primLeFloat         Float -> Float -> Bool
  5494.  
  5495.  
  5496. .cc 5
  5497. generic      primGenericEq       a -> a -> Bool
  5498. ordering     primGenericNe       a -> a -> Bool
  5499. primitives   primGenericGt       a -> a -> Bool
  5500.              primGenericLe       a -> a -> Bool
  5501.              primGenericGe       a -> a -> Bool
  5502.              primGenericLt       a -> a -> Bool
  5503.  
  5504.              These functions implement the standard generic  (i.e.  non
  5505.              overloaded) ordering primitives.  They are  not  currently
  5506.              used in the standard prelude.  A simplified prelude may be
  5507.              created by binding the  standard  operator  symbols  (==),
  5508.              (/=),  (>),  (<=),  (>=)  and  (<)  to   these   functions
  5509.              respectively.
  5510.  
  5511. output       primPrint           Int -> a -> String -> String
  5512.  
  5513.              This function is used to implement the show'  function  in
  5514.              the standard prelude and is not usually used directly.
  5515.  
  5516.              primPrint d e s produces a textual representation  of  the
  5517.              value of the expression e as a  string,  followed  by  the
  5518.              string s.  The integer parameter d is used as an indicator
  5519.              of the current precedence level.  The  primPrint  function
  5520.              is the  standard  method  of  printing  the  value  of  an
  5521.              expression whose type is not equivalent to the type String
  5522.              used by the top-level of the Gofer interpreter.
  5523.  
  5524. sequencing   primStrict          (a -> b) -> a -> b
  5525.  
  5526.              The primStrict function (bound to the identifier  "strict"
  5527.              in the standard prelude)  forces  the  evaluation  of  its
  5528.              second argument before the function supplied as the  first
  5529.              argument is  applied  to  it.   See  section  9.4  for  an
  5530.              illustration.
  5531.  
  5532. .pa
  5533. .>appx_f
  5534. .ST APPENDIX F: INTERPRETER COMMAND SUMMARY
  5535.  
  5536. Command      Description
  5537. -------      -----------
  5538. <expr>       Analyse expression for errors, typecheck and evaluate.  If
  5539.              the expression has type Dialogue,  execute  as  a  program
  5540.              using the I/O facilities as described in section  12.   If
  5541.              the expression has type String, evaluate and print  result
  5542.              as a lazy list of characters.   In  any  other  case,  the
  5543.              standard  prelude  function  show'  is  applied   to   the
  5544.              expression and used to print the value of  the  result  in
  5545.              the form of a string, as in the previous case.
  5546.  
  5547. :t <expr>    Analyse expression for errors,  typecheck  and  print  the
  5548. :type <expr> translation and inferred type of the term.
  5549. :T
  5550.  
  5551. :q           Exit Gofer interpreter.
  5552. :quit
  5553. :Q
  5554.  
  5555. :?           Display summary of interpreter commands.
  5556. :h
  5557. :H
  5558.  
  5559. :l f1 .. fn  Removes any previously loaded  files  of  definitions  and
  5560.              attempts to load the contents of the files f1 upto fn  one
  5561.              after the other.
  5562.  
  5563. :L           Remove any previously loaded files of  definitions.   Only
  5564.              those functions and values defined in the standard prelude
  5565.              will still be be available.
  5566.  
  5567. :load        Equivalent forms of the :l command.
  5568. :L
  5569.  
  5570. :a f1 .. fn  Load the contents of the files f1 upto fn in  addition  to
  5571.              any previously loaded files.   If  any  of  the  files  of
  5572.              definitions which  have  already  been  loaded  have  been
  5573.              modified  since  they  were   last  read   then  they  are
  5574.              automatically reloaded before any of the files f1 upto  fn
  5575.              are read.
  5576.  
  5577.              If successful, a command of  the  form  ":l  f1  ..fn"  is
  5578.              equivalent to the sequence of commands:
  5579.                                :l
  5580.                                :a f1
  5581.                                 .
  5582.                                 .
  5583.                                :a fn
  5584.  
  5585. :also        Equivalent forms of the :a command.
  5586. :A
  5587.  
  5588. :r           Repeat the last load command,  attempting  to  reload  any
  5589.              files which have subsequently been modified.  Since  later
  5590.              files may depend on the definitions in earlier ones,  once
  5591.              one file has been reloaded, all subsequent files will also
  5592.              need to be reloaded.
  5593.  
  5594. :reload      Equivalent forms of the :r command.
  5595. :R
  5596.  
  5597. :e file      Suspend current Gofer session and start an editor  program
  5598.              to modify or view the named file.  The Gofer session  will
  5599.              be resumed when the editor  program  terminates,  and  any
  5600.              script files that  have  been  changed  will  be  reloaded
  5601.              automatically.
  5602.  
  5603.              Note that a separate editor program is required  and  that
  5604.              Gofer must be properly installed to use this feature.  The
  5605.              default editor is usually vi (Calvin version 2.0 is a good
  5606.              substitute for a PC), although this may have been  changed
  5607.              when your system was installed.   In  any  case,  you  can
  5608.              always substitute an editor of your choice by setting  the
  5609.              environment variable EDITOR to the name of your  favourite
  5610.              editor program.
  5611.  
  5612.              There are a number  of  factors  which  will  affect  your
  5613.              choice of editor.  On a slow machine, with only a  limited
  5614.              amount of memory, you  will  probably  need  to  choose  a
  5615.              relatively small editor which  can  be  loaded  reasonably
  5616.              quickly and does not require too much memory.  On  a  more
  5617.              powerful system, you may find it more  convenient  to  use
  5618.              Gofer from a window based environment, running your editor
  5619.              in one window with Gofer in another.
  5620.  
  5621. :e           Using the :e command without specifying a particular  file
  5622.              to be edited starts up  an  editor  program  as  described
  5623.              above either for the file  of  definitions  most  recently
  5624.              loaded into Gofer or, if an error occurred whilst  loading
  5625.              a file of definitions, for  the  file  of  definitions  in
  5626.              which the error was last detected.
  5627.  
  5628.              With many editor programs, it is even  possible  to  start
  5629.              the editor at the  line  where  the  error  occurred.   As
  5630.              before, it is possible to change the default behaviour  of
  5631.              Gofer in this case by  setting  the  environment  variable
  5632.              EDITLINE to a command string which can be  used  to  start
  5633.              the editor program with a given file at  a  specific  line
  5634.              number.  The positions in the string  at  which  the  file
  5635.              name and line number values should be inserted  should  be
  5636.              indicated by the strings "%s" and "%d"  respectively,  and
  5637.              may appear in either order.  The default  command  string,
  5638.              which is used if EDITLINE is not set is "vi +%d %s".
  5639.  
  5640. :edit        Equivalent forms of the :e command.
  5641. :E
  5642. .pa
  5643. .>appx_g
  5644. .ST APPENDIX G: BIBLIOGRAPHY
  5645.  
  5646. [1]  Introduction to functional programming, Richard  Bird  and  Philip
  5647.      Wadler, Prentice Hall International, 1989.
  5648.  
  5649. [2]  The Implementation of functional programming languages,  Simon  L.
  5650.      Peyton Jones, Prentice Hall International, 1987.
  5651.  
  5652. [3]  Lambda Lifting:  Transforming  Programs  to  Recursive  Equations,
  5653.      Thomas  Johnsson,  in  Lecture  Notes  in  Computer  Science  201,
  5654.      Springer Verlag, 1985.  [but try to get a copy of the  version  of
  5655.      this paper included in Johnsson's thesis which  benefits  from  an
  5656.      extended typeface and is a little easier to read!]
  5657.  
  5658. [4]  How to make ad-hoc polymorphism less  ad-hoc,  Philip  Wadler  and
  5659.      Stephen Blott, University of Glasgow, in the  proceedings  of  the
  5660.      16th ACM annual symposium on Principles of Programming  Languages,
  5661.      Austin, Texas, January 1989.
  5662.  
  5663. [5]  Report on the programming language Haskell,  a  non-strict  purely
  5664.      functional language (Version 1.1), Paul Hudak,  Philip  Wadler  et
  5665.      al.  Technical report Yale University/Glasgow University.  August,
  5666.      1991.
  5667.  
  5668. [6]  Introduction to Orwell 6.00, Philip  Wadler  and  Quentin  Miller,
  5669.      University of Oxford, 1990.
  5670.  
  5671. [7]  Lazy ML user's manual, Lennart  Augustsson  and  Thomas  Johnsson,
  5672.      1990.
  5673.  
  5674. [8]  Computing with lattices: An application of type classes,  Mark  P.
  5675.      Jones, Technical report PRG-TR-11-90, Programming Research  Group,
  5676.      Oxford University Computing Laboratory, June 1990.
  5677.  
  5678. [9]  Towards a theory of qualified  types,  Mark  P.  Jones,  Technical
  5679.      report PRG-TR-6-91, Programming Research Group, Oxford  University
  5680.      Computing Laboratory, April 1991.
  5681.  
  5682. [10] Type inference for  qualified  types,  Mark  P.  Jones,  Technical
  5683.      report PRG-TR-10-91, Programming Research Group, Oxford University
  5684.      Computing Laboratory, June 1991.
  5685.  
  5686. [11] A new approach to type classes,  Mark  P.  Jones,  distributed  to
  5687.      Haskell mailing list 1991.
  5688.  
  5689. [12] Practical issues in the implementation of qualified types, Mark P.
  5690.      Jones, Forthcoming 1991.
  5691.