home *** CD-ROM | disk | FTP | other *** search
/ ftp.uni-stuttgart.de/pub/systems/acorn/ / Acorn.tar / Acorn / acornet / dev / gofer.spk / docsrc / doc228 < prev    next >
Text File  |  1994-06-06  |  115KB  |  2,758 lines

  1. .co This is the source form of the release notes for Gofer 2.28
  2. .co
  3. .co Mark P Jones January 1993
  4. .co-------------------------------------------------------------------|
  5. .>release.228
  6. -----------------------------------------------------------------------
  7.        __________   __________   __________   __________   ________
  8.       /  _______/  /  ____   /  /  _______/  /  _______/  /  ____  \
  9.      /  / _____   /  /   /  /  /  /______   /  /______   /  /___/  /
  10.     /  / /_   /  /  /   /  /  /  _______/  /  _______/  /  __   __/
  11.    /  /___/  /  /  /___/  /  /  /         /  /______   /  /  \  \ 
  12.   /_________/  /_________/  /__/         /_________/  /__/    \__\
  13.  
  14.   Functional programming environment, Version 2.28
  15.  
  16.   Copyright Mark P Jones 1993.
  17.  
  18.   Release notes
  19. -----------------------------------------------------------------------
  20.  
  21. This document is intended to be used as a supplement to the original
  22. user manual ``An introduction to Gofer version 2.20'' and release
  23. notes for Gofer 2.21 (previously supplied in a file called `update').
  24.  
  25. If you would like to be informed when bug-fixes or further versions
  26. become available, please contact me at jones-mark@cs.yale.edu (if you
  27. have not already done so) and I will add your name to the list.
  28.  
  29. Please contact me if you have any questions about the Gofer system, or
  30. if you need some advice or help to complete a port of Gofer to a new
  31. platform.
  32.  
  33.  
  34. ACKNOWLEDGMENTS:
  35. A lot of people have contributed to the development of Gofer 2.28 with
  36. their support, encouragement, suggestions, comments and bug reports.
  37. There are a lot of people to thank:
  38.  
  39.                  Ray Bellis            Brent Benson
  40.                David Bolton           Rodney Brown
  41.                 Dave Cattrall         Manuel Chakravarty
  42.                 Rami El Charif        Stuart Clayman
  43.                 Andy Duncan            Bernd Eckenfels
  44.              Stephen Eldridge         Jeroen Fokker
  45.                 Andy Gill             Annius Groenink
  46.             Dipankar Gupta           Guenter Huebel
  47.                  Jon Hallett           Kevin Hammond
  48.                Peter Hancock             Ian Holyer
  49.               Andrew Kennedy          Marnix Klooster
  50.                  Tom Lane           Hiroyuki Matsuda
  51.                Aiden McCaughey        Tobias Nipkow
  52.               Rainer Orth               Will Partain
  53.                Simon Peyton Jones        Ian Poole
  54.                 Mark Raemer             Dave Rushall
  55.               Julian Seward            Carol Tumey
  56.                Goran Uddeborg          Gavin Wraith
  57.                Bryan Scattergood     Matthew Smith
  58.              Bernard Sufrin           Philip Wadler
  59.  
  60. This list isn't complete, and I apologize in advance if I have
  61. inadvertently left your name out.
  62. .pa
  63. .ti Release Notes v2.28
  64. .co-------------------------------------------------------------------|
  65. .ST 1. MINOR ENHANCEMENTS AND BUGFIXES
  66.  
  67. The following sections list the minor enhancements and bugfixes that
  68. have been made to Gofer since the release of Gofer version 2.23.  More
  69. significant changes are described in later sections.
  70.  
  71.  
  72. .ST 1.1  Enhancements
  73. -----------------
  74.   o  For systems without the restrictions of older PCs, Gofer now uses
  75.      multiple hash tables to speed the lookup of globally defined
  76.      functions.  Loading large programs into Gofer is now much faster
  77.      as a result.  In one example, the time taken to load a 13,000 line
  78.      program spread across 40 individual script files was reduced by a
  79.      factor of five!
  80.  
  81.   o  For the most most part, internal errors (which shouldn't normally
  82.      appear anyway) no longer terminate the interpreter.
  83.  
  84.   o  Better handling for programs with objects whose type involves more
  85.      than 26 type variables (though whether anyone has real practical
  86.      applications for such beasts, I'm rather doubtful).
  87.  
  88.   o  The Gofer system now supports I/O requests GetProgName, GetArgs
  89.      and GetEnv.  The first two requests don't have any sensible
  90.      interpretation within the interpreter, so GetProgName always
  91.      returns "", while GetArgs returns [].  These I/O requests are most
  92.      useful when producing standalone applications with the Gofer
  93.      compiler where they do indeed give the name of the program and the
  94.      list of command line arguments as expected.
  95.  
  96.   o  Added primitives for direct comparison of characters.  The
  97.      original definitions of character equality and ordering in terms
  98.      of the equality and ordering on integers was elegant, but for some
  99.      examples, a substantial number of the total reductions in a given
  100.      program was taken up with calls to ord, an unnecessary
  101.      distraction.
  102.  
  103.   o  Small improvements in the speed of execution of the runtime machine,
  104.      particularly when Gofer is compiled using the GNU C compiler.
  105.  
  106.   o  Enabled the use of GNU C specific options to store frequently used
  107.      global variables in CPU registers.  This is perhaps most useful
  108.      for speeding up the performance of standalone applications
  109.      produced using the Gofer compiler.
  110.  
  111.   o  Changed definitions in standard preludes to provide overloaded
  112.      versions of sum, product, sums, products, abs, signum and (^).
  113.      Also added a genericLength function as in Haskell.  Finally,
  114.      added Text as a superclass of Num, again for Haskell compatibility.
  115.  
  116.   o  Added a new primitive function: openfile :: String -> String that
  117.      can be used to read the contents of a file (named by the argument
  118.      string) as a (lazy) stream of characters.  (The implementation is
  119.      in terms of a primitive which can also be used to implement the
  120.      hbc openFile function, provided that you also define the Either
  121.      datatype used there.)
  122.  
  123.   o  Added support for a simple selection of operators for monadic I/O,
  124.      mutable variables etc. based on Lambda var (developed at Yale) and
  125.      the Glasgow I/O system.  I will provide more documentation on this
  126.      as soon as there is a better consensus on the names of the
  127.      datatypes and functions that should be included in systems like
  128.      this.
  129.  
  130.   o  The error function is now implemented using a primitive function.
  131.  
  132.   o  Added support for floating point primitives:
  133.  
  134.          pi          :: Float
  135.  
  136.          sin, asin,
  137.          cos, acos,
  138.          tan, atan,
  139.          log, log10,
  140.          exp, sqrt   :: Float -> Float
  141.  
  142.          atan2       :: Float -> Float -> Float
  143.          truncate    :: Float -> Int
  144.  
  145.   o  Added support for the use of GNU readline (or equivalent) library
  146.      to be used to enhance the user interface with command line
  147.      editing.  See the source makefile for instructions on how to use
  148.      this.
  149.  
  150.   o  Added floating point support to PC version of Gofer (even the
  151.      version for humble 8086 PCs will now support floating point).
  152.      Thanks to Jeroen Fokker for this!
  153.  
  154.   o  I/O datatype definitions and otherwise symbol are now builtin to
  155.      the Gofer system.
  156.  
  157.   o  Other minor tweaks and improvements.
  158.  
  159.  
  160. .ST 1.2  Bug fixes
  161. --------------
  162. Nobody really likes to dwell on bugs, especially when they have been
  163. eliminated.  But for those of you who want to know, here is a summary of
  164. the bugs discovered and fixed in Gofer 2.28:
  165.  
  166.   o  End of file does not imply end of line (only significant on
  167.      certain systems ... I has made an assumption which happens to hold
  168.      under DOS and Unix, but was not true for other systems).
  169.  
  170.   o  Code generator produced incorrect code for some conditional
  171.      expressions involving local variables (fairly obscure).
  172.  
  173.   o  Some conditional expressions entered into the interpreter were
  174.      evaluated incorrectly, leading to unexpected evaluation errors.
  175.  
  176.   o  A small potential space leak concerned with saving the names of
  177.      files passed to the editor from within Gofer was eliminated.
  178.  
  179.   o  A subtle bug, which only occurred when a garbage collection
  180.      occurred in the middle of an attempt to update a cell with an
  181.      indirection has been fixed.
  182.  
  183.   o  Fixing the definitions of the div and quot operators to agree with
  184.      Haskell 1.2 (these had been changed in the transition from 1.1 to
  185.      1.2 without my noticing).
  186.  
  187.   o  Corrected bug in string matching code (part of the :names command)
  188.      which previously allowed "*e*p" to match with "negate"!
  189.  
  190.   o  Nested comments were not always handled correctly when they
  191.      occurred at the very end of a script file.
  192.  
  193.   o  Added new clauses to parser to improve and correct error messages
  194.      produced by some examples.
  195.  
  196.   o  Other miscellaneous tweaks and fixes.
  197.  
  198. There are no other currently known bugs in Gofer.  But someone is bound
  199. to find a new one within hours of the release of 2.28 if past
  200. experience is anything to go by.  If that someone is you, please let me
  201. know!
  202.  
  203.  
  204. .co-------------------------------------------------------------------|
  205. .ST 2. USER INTERFACE EXTENSIONS
  206.  
  207. The user interface of the previous release has been extended a little
  208. to support a range of new features, intended to make the Gofer
  209. environment more convenient for program development.  Further details
  210. are given in the following sections.
  211.  
  212. .ST 2.1  Customizing the Gofer system
  213. ---------------------------------
  214. Often there will be several people using Gofer on the same system.  Not
  215. everyone will want to be using the system in the same way.  For example,
  216. some users may wish to use their own version of the prelude or start the
  217. interpreter with particular command line options.
  218.  
  219. It has always been possible to do this by installing Gofer in an
  220. appropriate manner.  But, having had more than a couple of enquiries
  221. about this, I wanted to take some time to spell the process out more
  222. clearly.  The following description will be biased towards those people
  223. using Gofer on Unix-like systems, but the same basic principles can be
  224. applied with other operating systems too.
  225.  
  226. The Gofer interpreter and prelude files will typically be installed in
  227. a given directory, accessible to all users on the system.  For the sake
  228. of this example, let's assume that this is /usr/local/lib/Gofer.  Each
  229. user could take a copy of the Gofer interpreter into their own file
  230. space, but a much better option is for each user to use a short script
  231. file stored somewhere on their path.  For example, the path on my Unix
  232. account includes a subdirectory called bin and I store the following
  233. script file `gofer' in this directory:
  234.  
  235.     #!/bin/sh
  236.     #
  237.     # A simple shell script to invoke the Gofer interpreter and set
  238.     # the path to the prelude file.  Ultimately, you might want to
  239.     # copy this file into your own bin directory so that you can record
  240.     # your favourite command line settings or use a different prelude
  241.     # file ...
  242.     #
  243.     GOFER=/usr/local/lib/Gofer/standard.prelude
  244.     export GOFER
  245.     exec /usr/local/lib/Gofer/gofer $*
  246.  
  247. I happen to use the standard prelude file and the default settings for
  248. all the command line options.  If, for example, I wanted to use a
  249. different prelude file, a smaller heap and omit the printing of
  250. statistics about the number of reductions and cells used in an
  251. evaluation, I can modify the script to reflect this:
  252.  
  253.     #!/bin/sh
  254.     #
  255.     # A modified version of the above script
  256.     #
  257.     GOFER=/usr/local/lib/Gofer/simple.prelude
  258.     export GOFER
  259.     exec /usr/local/lib/Gofer/gofer -h20000 -s $*
  260.  
  261. Of course, it is also possible to keep both of these short scripts in
  262. my bin directory, so that I have the choice of starting up Gofer in
  263. several different configurations, depending on the kind of work I'm
  264. going to be doing with it.
  265.  
  266.  
  267. .ST 2.2  Command line options
  268. --------------------------
  269. Gofer 2.28 supports a number of options which can be set, either on the
  270. command line when Gofer interpreter is started, or using the :set
  271. command within in the interpreter.  Using the :set command without any
  272. arguments produces a list of all the command line options available:
  273.  
  274.    ? :set
  275.    TOGGLES: groups begin with +/- to turn options on/off resp.
  276.    s    Print no. reductions/cells after eval
  277.    t    Print type after evaluation
  278.    d    Show dictionary values in output exprs
  279.    f    Terminate evaluation on first error
  280.    g    Print no. cells recovered after gc
  281.    c    Test conformality for pattern bindings
  282.    l    Literate scripts as default
  283.    e    Warn about errors in literate scripts
  284.    i    Apply fromInteger to integer literals
  285.    o    Optimise use of (&&) and (||)
  286.    u    Catch ambiguously typed top-level vars
  287.    .    Print dots to show progress
  288.    w    Always show which files loaded
  289.    1    Overload singleton list notation
  290.    k    Show kind errors in full
  291.  
  292.    OTHER OPTIONS: (leading + or - makes no difference)
  293.    hnum Set heap size (cannot be changed within Gofer)
  294.    pstr Set prompt string to str
  295.    rstr Set repeat last expression string to str
  296.  
  297.    Current settings: +sfceow1 -tdgliu.k -h100000 -p? -r$$
  298.    ?
  299.  
  300. Most of these are the same as in the previous release of Gofer.  The
  301. following sections outline the few changes that have been made.  The
  302. `1' and `k' toggles are for use with constructor classes and will be
  303. described in Section 4.
  304.  
  305.  
  306. .ST 2.2.1  Print dots to show progress
  307. ----------------------------------
  308. One of the first differences that you might notice when running the
  309. new version of Gofer is that the rows of dots printed when loading a
  310. script file:
  311.  
  312.     ? :l examples
  313.     Reading script file "examples":
  314.     Parsing....................................
  315.     Dependency analysis........................
  316.     Type checking..............................
  317.     Compiling..................................
  318.  
  319.     Gofer session for:
  320.     /usr/local/lib/Gofer/standard.prelude
  321.     examples
  322.     ?
  323.  
  324. are no longer printed while script files are loaded.  The rows of dots
  325. are useful for showing progress on slow machines (like the PC on which
  326. Gofer was originally developed) where it is reassuring to know that the
  327. system has not crashed, and is simply working its way through one
  328. particular phase of the system.  However, on a faster system, the dots
  329. are not necessary and printing them can impose a surprising overhead on
  330. the time it takes to load files.  As a default, Gofer now simply prints
  331. the names of each phase (Parsing, Dependency Analysis, Type checking
  332. and Compiling) and, when that phase is complete, backspaces over it to
  333. erase it from the screen.  If you are fortunate enough to be using a
  334. fast machine, you may not always see the individual words as they flash
  335. past.  After loading a file, your screen will typically look something
  336. like this:
  337.  
  338.     ? :l examples
  339.     Reading script file "examples":
  340.                    
  341.     Gofer session for:
  342.     /usr/local/lib/Gofer/standard.prelude
  343.     examples
  344.     ?
  345.  
  346. On some systems, the use of backspace characters to erase a line may
  347. not work properly.  One particular example of this occurs if you try to
  348. run Gofer from within emacs.  In this case, you may prefer to use the
  349. original setting, printing the lines of dots by giving the command:
  350.  
  351.     :set +.
  352.  
  353. The default setting is (as illustrated above, :set -.).  In practice,
  354. you will probably want to include the appropriate setting for this
  355. option in your startup script (see Section 2.1).
  356.  
  357.  
  358. .ST 2.2.2  Always show which files loaded
  359. -------------------------------------
  360. Some people may feel that the list of filenames printed by Gofer after
  361. successfully loading one or more script files is redundant.  This is
  362. particularly likely if you are using the (usually default) :set -.
  363. option since the list of files loaded will probably still be on the
  364. screen.  The list of filenames can be suppressed using the :set -w
  365. option as follows:
  366.  
  367.     ? :l examples
  368.     Reading script file "examples":
  369.                    
  370.     Gofer session for:
  371.     /usr/local/lib/Gofer/standard.prelude
  372.     examples
  373.     ? :set -w
  374.     ? :l examples
  375.     Reading script file "examples":
  376.     ?
  377.  
  378. The default setting can be recovered using a :set +w command.
  379.  
  380. Note that you can also use the :info command (without any arguments) as
  381. described in Section 2.3.2 to find out the list of files loaded into the
  382. current Gofer session.  This should be particularly useful if you choose
  383. the :set -w option.
  384.  
  385.  
  386. .ST 2.2.3  Set repeat string
  387. ------------------------
  388. The previous expression entered into the Gofer system can be recalled
  389. as part of the next expression using the symbol $$:
  390.  
  391.     ? map (1+) [1..10]
  392.     [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
  393.     (101 reductions, 189 cells)
  394.     ? filter even $$
  395.     [2, 4, 6, 8, 10]
  396.     (130 reductions, 215 cells)
  397.     ?
  398.  
  399. This feature was provided and documented in the previous release of
  400. Gofer.  However, it is possible that you may prefer to use a different
  401. character string.  This is the purpose of the -rstr option which sets
  402. the repeat string to str.  For example, user's of SML might be more
  403. comfortable using:
  404.  
  405.     ? :set -rit
  406.     ? 6*7
  407.     42
  408.     (3 reductions, 7 cells)
  409.     ? it + it
  410.     84
  411.     (4 reductions, 11 cells)
  412.     ?
  413.  
  414. Another reason for making this change might be that you have a program
  415. which uses the symbol $$ as an operator.  Each occurrence of the $$ symbol
  416. in a script file will be interpreted as the correct operator, whatever
  417. the value of the repeat string.  But, if the default :set -r$$ setting is
  418. used, any occurrence of $$ in an expression entered directly to the
  419. evaluator will be taken as a reference to the previous expression.
  420.  
  421. Note that the repeat string must be either a valid Haskell identifier or
  422. symbol, although it will always be parsed as an identifier.  If the
  423. repeat string is set to a value which is neither an identifier or symbol
  424. (for example, :set -r0) then the repeat last expression facility will be
  425. disabled altogether.
  426.  
  427.  
  428. .ST 2.2.4  Other changes
  429. --------------------
  430. Comparing the list of command line options in Section 2.2 with the list
  431. produced by previous versions of Gofer will reveal some other small
  432. differences not already mentioned above.  The changes are as follows:
  433.  
  434.   o  The default setting for the d toggle (show dictionaries in output
  435.      expressions) has been changed to off (:set -d).  For a lot of
  436.      people, the appearance of dictionary values was rather confusing
  437.      and of little use.  If you still want to see how dictionary values
  438.      are used, you will need to do :set +d or add the +d argument to
  439.      your startup script.
  440.  
  441.   o  The default setting for the e toggle (warn about errors in
  442.      literate scripts) has been changed to :set +e for closer
  443.      compatibility with the literate script convention outline in the
  444.      Haskell report, version 1.2.  In addition, the setting of the l
  445.      toggle is now used only as a default if no particular type of
  446.      script file is specified by the file extension of a give script.
  447.      See Section 2.4 below for further details.
  448.  
  449.   o  The default setting for the f toggle (terminate evaluation on
  450.      first error) has been changed to :set +f.  The old setting of
  451.      :set -f is, in my opinion, better for debugging purposes, but
  452.      does not give the behaviour that those using Haskell might
  453.      expect.  This has caused a certain amount of confusion and was
  454.      the motivation for this change.
  455.  
  456.   o  The following three command line options, provided in previous
  457.      versions of Gofer, have now been removed:
  458.  
  459.          TOGGLES:
  460.          a    Use any evidence, not nec. best
  461.          E    Fail silently if evidence not found
  462.  
  463.          OTHER OPTIONS:
  464.          xnum Set maximum depth for evidence search
  465.  
  466.      These options were only ever used for my own research and were
  467.      (intentionally) undocumented, so it seemed sensible to remove them
  468.      from the distributed system.  A quick patch to the source code and
  469.      a recompilation is all that is necessary to reinstate these
  470.      options; useful if somebody out there found out about these
  471.      options and actually uses them (if you do, I'd love to know
  472.      why!).
  473.  
  474.  
  475. .ST 2.3  Commands
  476. -------------
  477. The full list of commands that can be used from within the Gofer
  478. interpreter are summarized using the command :? as follows:
  479.  
  480.     ? :?
  481.     LIST OF COMMANDS:  Any command may be abbreviated to :c where
  482.     c is the first character in the full name.
  483.  
  484.     :load <filenames>   load scripts from specified files
  485.     :load               clear all files except prelude
  486.     :also <filenames>   read additional script files
  487.     :reload             repeat last load command
  488.     :project <filename> use project file
  489.     :edit <filename>    edit file
  490.     :edit               edit last file
  491.     <expr>              evaluate expression
  492.     :type <expr>        print type of expression
  493.     :?                  display this list of commands
  494.     :set <options>      set command line options
  495.     :set                help on command line options
  496.     :names [pat]        list names currently in scope
  497.     :info <names>       describe named objects
  498.     :find <name>        edit file containing definition of name
  499.     :!command           shell escape
  500.     :cd dir             change directory
  501.     :quit               exit Gofer interpreter
  502.     ?
  503.  
  504. Almost all of these commands are the same as in the previous release.
  505. The only new features are listed in the following sections.
  506.  
  507.  
  508. .ST 2.3.1  Shell escapes
  509. --------------------
  510. The shell escape command :! is used to enable you to run other programs
  511. from within the Gofer interpreter.  For example, on a Unix system, you
  512. can print a list of all the files in the current directory by typing:
  513.  
  514.     ? :!ls
  515.     <list of all files in current directory gets printed here>
  516.     ?
  517.  
  518. The same thing can be achieved on a PC running DOS by typing:
  519.  
  520.     ? :!dir
  521.     <list of all files in current directory gets printed here>
  522.     ?
  523.  
  524. This is the same as in previous releases of Gofer; the only difference
  525. is that there is no longer any need to type a space between the :!
  526. command and the shell command that follows it.  In fact, there is no
  527. longer any need to type the leading colon either.  Thus the two commands
  528. above could equally well have been entered as:
  529.  
  530.     !ls
  531.     !dir
  532.  
  533. To start a new shell from within Gofer, you can use the command :! or the
  534. abbreviated form ! -- in Unix and DOS you can return to the Gofer system
  535. by entering the shell command `exit'.  This is likely to be different if
  536. you use Gofer on other systems.
  537.  
  538.  
  539. .ST 2.3.2  Information about named values
  540. -------------------------------------
  541. The :info command is a new feature which is useful for obtaining
  542. information about the values currently loaded into a Gofer session.  It
  543. can be used to display information about all kinds of different values
  544. including:
  545.  
  546.   o  Datatypes:  The name of the datatype and a list of its associated
  547.      constructor functions is printed:
  548.  
  549.          ? :info Request
  550.          -- type constructor
  551.          data Request
  552.  
  553.          -- constructors:
  554.          ReadFile :: String -> Request
  555.          WriteFile :: String -> String -> Request
  556.          AppendFile :: String -> String -> Request
  557.          ReadChan :: String -> Request
  558.          AppendChan :: String -> String -> Request
  559.          Echo :: Bool -> Request
  560.          GetArgs :: Request
  561.          GetProgName :: Request
  562.          GetEnv :: String -> Request
  563.  
  564.          ?
  565.  
  566.   o  Type synonyms:  Prints the name and expansion of the synonym:
  567.  
  568.          ? :info Dialogue
  569.          -- type constructor
  570.          type Dialogue = [Response] -> [Request]
  571.  
  572.          ?
  573.  
  574.      If the type synonym is restricted (see Section 3.1) then the
  575.      expansion is not included in the output:
  576.  
  577.          ? :info Stack      
  578.          -- type constructor
  579.          type Stack a = <restricted>
  580.  
  581.          ?
  582.  
  583.   o  Type classes: Lists the type class name, superclasses, member
  584.      functions and instances:
  585.  
  586.          ? :info Eq
  587.          -- type class
  588.          class Eq a where
  589.              (==) :: Eq a => a -> a -> Bool
  590.              (/=) :: Eq a => a -> a -> Bool
  591.  
  592.          -- instances:
  593.          instance Eq ()
  594.          instance Eq Int
  595.          instance Eq Float
  596.          instance Eq Char
  597.          instance Eq a => Eq [a]
  598.          instance (Eq a, Eq b) => Eq (a,b)
  599.          instance Eq Bool
  600.  
  601.          ?
  602.  
  603.      Note that the member functions listed for the class include the
  604.      class predicate as part of the type; the output is not intended
  605.      to be thought of as a syntactically valid class declaration.
  606.  
  607.      Overlapping instance declarations (see Section 3.2) are listed in
  608.      increasing order of generality.
  609.  
  610.   o  Other values: for example, named functions and individual
  611.      constructor and member functions:
  612.  
  613.          ? :info map : <=
  614.          map :: (a -> b) -> [a] -> [b]
  615.  
  616.          (:) :: a -> [a] -> [a]   -- data constructor
  617.  
  618.          (<=) :: Ord a => a -> a -> Bool   -- class member
  619.  
  620.          ?
  621.  
  622. As the last example shows, the :info command can take several arguments
  623. and prints out information about each in turn.  A warning message is
  624. displayed if there are no known references to an argument:
  625.  
  626.     ? :info (:)
  627.     Unknown reference `(:)'
  628.     ?
  629.  
  630. This illustrates that the arguments are treated as textual names for
  631. operators, not syntactic expressions (for example, identifiers). The
  632. type of the (:) operator can be obtained by giving the command :info :
  633. as above.  There is no provision for including wildcard characters of
  634. any form in the arguments of :info commands.
  635.  
  636. If a particular argument can be interpreted as, for example, a
  637. constructor function, or a type constructor depending on context, both
  638. possibilities are displayed.  For example, loading a program containing
  639. the definition:
  640.  
  641.     data Set a = Set [a]
  642.  
  643. We obtain:
  644.  
  645.     ? :info Set        
  646.     -- type constructor
  647.     data Set a
  648.  
  649.     -- constructors:
  650.     Set :: [a] -> Set a
  651.  
  652.     Set :: [a] -> Set a   -- data constructor
  653.  
  654.     ?
  655.  
  656. If no arguments are supplied to :info, a list of all the script files
  657. currently loaded into the interpreter will be displayed:
  658.  
  659.     ? :info
  660.  
  661.     Gofer session for:
  662.     /usr/local/lib/Gofer/standard.prelude
  663.     examples
  664.     ?
  665.  
  666.  
  667. .ST 2.4  Literate scripts
  668. ---------------------
  669. Support for literate scripts -- files in which program lines begin with
  670. a `>' character and all other lines are treated as comments -- was
  671. provided in previous versions of Gofer.  The command line option
  672. :set +l was used to force Gofer to treat each input file as a literate
  673. script, while :set -l (the default) was used to treat each input file
  674. as a standard script of definitions.
  675.  
  676. In practice, this turned out to be somewhat inconvenient, particularly
  677. when loading combinations of files, some as literate scripts, some
  678. without.  For example, quite a few people kept two versions of the
  679. prelude, one as a literate script, one not, so that they wouldn't have
  680. to fiddle with the settings or using the :set commands to load files.
  681.  
  682. Gofer version 2.28 now uses a more sophisticated scheme to determine
  683. how an input script file should be treated, based on the use of file
  684. extensions.  More specifically, any script file with a name ending in
  685. one of the following suffixes:
  686.  
  687.     .hs     .has    .gs     .gof    .prelude
  688.  
  689. will always be loaded as a normal (i.e. non-literate) script file,
  690. regardless of the setting of the l command line option.  In a similar
  691. way, files with names ending in one of the following suffixes:
  692.  
  693.     .lgs    .lhs    .verb   .lit
  694.  
  695. will always be treated as literate scripts.  The command line option l
  696. is only used for files with names not ending in one of the above
  697. suffixes.
  698.  
  699. For example, the commands:
  700.  
  701.     :set -l
  702.     :load prog1.gs prog2 prog3.lgs
  703.  
  704. will load prog1.gs and prog2 as non-literate scripts, and then load
  705. prog3.lhs as a literate script.
  706.  
  707.  
  708. .ST 2.5  Prelude files
  709. ------------------
  710. The Gofer system comes with a standard prelude, and a small number of
  711. alternative preludes.  These have always been there, but a lot of
  712. people don't seem to have noticed these, so I thought I'd say a few
  713. words about the different preludes included with Gofer: Remember that
  714. you can always change the prelude you are using by setting the GOFER
  715. environment variable or by modifying a startup script as described in
  716. Section 2.1:
  717.  
  718.     standard.prelude    The standard Gofer prelude, using type classes
  719.                         and providing the familiar range of operators
  720.                         and functions.
  721.  
  722.     nofloat.prelude     A simplified version of the standard.prelude
  723.                         which does not include any floating point
  724.                         operators.  This is likely to be of most use
  725.                         for those using Gofer on PCs where memory is
  726.                         at a premium; compiling a version of the
  727.                         interpreter (or compiler runtime library)
  728.                         without floating point support can give an
  729.                         important saving.
  730.  
  731.     simple.prelude      A prelude file based on the standard prelude
  732.                         but without type classes.  Let me emphasize
  733.                         that point: YOU CAN USE GOFER WITHOUT HAVING
  734.                         TO LEARN ABOUT TYPE CLASSES :-)  Some people
  735.                         seem to take to the use of type classes right
  736.                         from the beginning.  For those that have
  737.                         problems understanding the technical details
  738.                         or even the motivation, the simple.prelude
  739.                         can be used to get you familiar with the syntax
  740.                         of the language and the basic principles.
  741.                         Then you can move up to the standard.prelude
  742.                         when you're ready.  The principle differences
  743.                         can be described by listing the types of
  744.                         commonly used operators in the simple.prelude:
  745.  
  746.                               (==) :: a -> a -> Bool
  747.                               (<=) :: a -> a -> Bool
  748.                               (<)  :: a -> a -> Bool
  749.                               (>=) :: a -> a -> Bool
  750.                               (>)  :: a -> a -> Bool
  751.                               (/=) :: a -> a -> Bool
  752.                               show :: a -> String
  753.                               (+)  :: Int -> Int -> Int
  754.                               (-)  :: Int -> Int -> Int
  755.                               (*)  :: Int -> Int -> Int
  756.                               (/)  :: Int -> Int -> Int
  757.  
  758.                         The resulting language is closer to the system
  759.                         in Bird and Wadler (and can be made closer
  760.                         still by editing the simple.prelude to use
  761.                         zipwith instead of zipWith etc...).
  762.  
  763.     cc.prelude          An extended version of the standard.prelude
  764.                         including support for a number of useful
  765.                         constructor classes.  Most of the examples
  766.                         and applications described in Section 4 are
  767.                         based on this prelude.
  768.  
  769.     min.prelude         A minimal prelude file.  If you really want to
  770.                         build a very small prelude for a particular
  771.                         application, start with this and add the extra
  772.                         things that you need.
  773.  
  774. As you can see, the standard extension for prelude files is .prelude
  775. and any file ending with this suffix will be read as a non-literate
  776. script (as described in Section 2.4).  Note that, even if you are using
  777. a computer where the full name of a prelude file is not stored (for
  778. example, on a DOS machine the standard.prelude file becomes
  779. STANDARD.PRE) you should still specify the prelude file by its full
  780. name to ensure that the Gofer system treats it correctly as a prelude
  781. file.
  782.  
  783. You are also free to construct your own prelude files, typically by
  784. modifying one of the supplied preludes described above.  Anyone who
  785. created prelude files for use with previous releases of Gofer will need
  786. to edit these files to ensure that they will work correctly.  Note in
  787. particular that there is no longer any need to include definitions of
  788. the I/O datatypes in programs.  Furthermore, the error function should
  789. now be bound to the primitive "primError" rather than using the old
  790. definition of error s | False = error s.
  791.  
  792.  
  793. .co-------------------------------------------------------------------|
  794. .ST 3. LANGUAGE DIFFERENCES
  795.  
  796. This section outlines a number of small differences and extensions to
  797. the language used by Gofer.  These features are not included in the
  798. definition of Haskell, so you shouldn't be thinking that programs
  799. written using these features can ultimately be used with a full Haskell
  800. system.  The use of constructor classes -- a more substantial change is
  801. described in Section 4.
  802.  
  803. .ST 3.1  Restricted type synonyms
  804. -----------------------------
  805. Gofer 2.28 supports a form of restricted type synonym that can be used
  806. to restrict the expansion of the synonym to a particular set of
  807. functions.  Outside of the selected group of functions, the synonym
  808. constructor behaves like a standard datatype.  More precisely, a
  809. restricted type synonym definition is a top level declaration of the
  810. form:
  811.  
  812.     type T a1 ... am = rhs in f1, ..., fn
  813.  
  814. where T is the name of the restricted type synonym constructor and rhs
  815. is a type expression typically involving some of the (distinct) type
  816. variables a1, ..., am.  The same kind of restrictions that apply to
  817. normal type synonym declarations are also applied here.  The major
  818. difference is that the expansion of the type synonym can only be used
  819. within the binding group of one of the functions f1, ..., fn (all of
  820. which must be defined by top-level definitions in the file containing
  821. the restricted type synonym definition).  In the definition of any
  822. other function, the type constructor T is treated as if it had been
  823. introduced by a definition of the form:
  824.  
  825.     data T a1 ... am = ...
  826.  
  827. The original motivation for restricted type synonyms came from my work
  828. with constructor classes as described in Section 4 and you will several
  829. examples of this in the ccexamples.gs file in the demos/Ccexamples
  830. directory of the standard distribution.  For a simpler example,
  831. consider the following definition of a datatype of stacks in terms of
  832. the standard list type:
  833.  
  834.     type Stack a = [a] in emptyStack, push, pop, top, isEmpty
  835.  
  836. The definitions for the five functions named here are as follows:
  837.  
  838.     emptyStack :: Stack a
  839.     emptyStack  = []
  840.  
  841.     push       :: a -> Stack a -> Stack a
  842.     push        = (:)
  843.  
  844.     pop        :: Stack a -> Stack a
  845.     pop []      = error "pop: empty stack"
  846.     pop (_:xs)  = xs
  847.  
  848.     top        :: Stack a -> a
  849.     top []      = error "top: empty stack"
  850.     top (x:_)   = x
  851.  
  852.     isEmpty    :: Stack a -> Bool
  853.     isEmpty     = null
  854.  
  855. The type signatures here are particularly important.  For example,
  856. since emptyStack is mentioned in the definition of the restricted type
  857. synonym Stack, the definition of emptyStack is type correct.  The
  858. declared type for emptyStack is Stack a which can be expanded to [a],
  859. agreeing with the type for the empty list [].  However, in an expression
  860. outside the binding group of these functions, the Stack a type is quite
  861. distinct from the [a] type:
  862.  
  863.     ? emptyStack ++ [1]
  864.     ERROR: Type error in application
  865.     *** expression     : emptyStack ++ [1]
  866.     *** term           : emptyStack
  867.     *** type           : Stack a
  868.     *** does not match : [Int]
  869.  
  870.     ?
  871.  
  872. The `binding group' of a value refers to the set of values whose
  873. definitions are in the same mutually recursive group of bindings.  In
  874. particular, this does not extend to the type class system so we can
  875. define instances such as:
  876.  
  877.     instance Eq a => Eq (Stack a) where
  878.         s1 == s2 | isEmpty s1 = isEmpty s2
  879.                  | isEmpty s2 = isEmpty s1
  880.                  | otherwise  = top s1 == top s2 && pop s1 == pop s2
  881.  
  882. As a convenience, Gofer allows the type signatures of functions
  883. mentioned in the type synonym declaration to be specified within the
  884. definition rather than in a different point in the script.  Thus the
  885. example above could equally well have been written as:
  886.  
  887.     type Stack a = [a] in
  888.         emptyStack :: Stack a,
  889.         push       :: a -> Stack a -> Stack a,
  890.         pop        :: Stack a -> Stack a,
  891.         top        :: Stack a -> a,
  892.         isEmpty    :: Stack a -> Bool
  893.  
  894.     emptyStack  = []
  895.  
  896.     push        = (:)
  897.  
  898.     pop []      = error "pop: empty stack"
  899.     pop (_:xs)  = xs
  900.  
  901.     top []      = error "top: empty stack"
  902.     top (x:_)   = x
  903.  
  904.     isEmpty     = null
  905.  
  906. However, the first form is necessary when you want to define two or
  907. more restricted type synonyms simultaneously.  For example:
  908.  
  909.     type Pointer = Int in allocate, deref, assign
  910.     type Heap a  = [a] in newHeap, allocate, deref, assign
  911.     newHeap  :: Heap a
  912.     allocate :: Heap a -> (Heap a, Pointer)
  913.     deref    :: Heap a -> Pointer -> a
  914.     assign   :: Heap a -> Pointer -> a -> Heap a
  915.     etc ...
  916.  
  917. The use of restricted type synonyms doesn't quite provide proper
  918. abstract data types.  For example, if you try:
  919.  
  920.     ? push 1 emptyStack
  921.     [1]
  922.     (5 reductions, 11 cells)
  923.     ?
  924.  
  925. then the structure of the stack as a list of values is revealed by the
  926. printing mechanism.  This happens because Gofer uses the show' function
  927. to print out a value (in this case of type Stack Int) which looks inside
  928. the structure of the object to see how it is represented.  This happens
  929. to be most convenient for use in an interpreter as an aid to debugging.
  930. For the purists (and the preservation of abstraction), Gofer could be
  931. modified to apply the (overloaded) show function to printed values.
  932. This would force the programmer to define the way in which stack values
  933. are printed (distinct from lists) and preserve the abstraction.  Without
  934. having set up this machinery, we get:
  935.  
  936.     ? show (push 1 emptyStack)
  937.     ERROR: Cannot derive instance in expression
  938.     *** Expression        : show (push 1 emptyStack)
  939.     *** Required instance : Text (Stack Int)
  940.  
  941.     ?
  942.  
  943. The Gofer compiler described in Section 5 does not implement show' and
  944. hence enforces the abstraction.
  945.  
  946.  
  947. .ST 3.2  Overlapping instance declarations
  948. --------------------------------------
  949. This section describes a somewhat technical extension, aimed at those
  950. who work with type classes.  Many readers may prefer to skip to the
  951. next section at this point.
  952.  
  953. The definition of Haskell and previous versions of Gofer insist that no
  954. two instance declarations for a given class may contain overlapping
  955. predicates.  Thus the declarations:
  956.  
  957.     class CX a where c :: a -> Int
  958.  
  959.     instance CX (a,Int) where c (x,y) = y
  960.     instance CX (Int,a) where c (x,y) = x
  961.  
  962. are not allowed because the two predicates overlap:
  963.  
  964.     ERROR "misctest" (line 346): Overlapping instances for class "CX"
  965.     *** This instance   : CX (Int,a)
  966.     *** Overlaps with   : CX (a,Int)
  967.     *** Common instance : CX (Int,Int)
  968.  
  969. As the error message indicates, given an expression c (1,2) it is not
  970. clear whether we should use the first or the second instance
  971. declarations to evaluate this, with potentially different results, 2 or
  972. 1 respectively.
  973.  
  974. On the other hand, there are cases where this sort of thing might be
  975. quite reasonable.  For example, the standard function show prints lists
  976. of characters as strings, but any other kind of list is printed using
  977. the [ ... ] notation with the items separated by commas:
  978.  
  979.     ? show "Hello"
  980.     "Hello"
  981.     ? show [True,False,True]
  982.     [True,False,True]
  983.     ? show [1..10]
  984.     [1,2,3,4,5,6,7,8,9,10]
  985.     ?
  986.  
  987. Haskell deals with this by an encoding using the showList function, but
  988. a more obvious approach might be to define two instances:
  989.  
  990.     instance Text a => Text [a] where ... print using [ ... ] notation
  991.     instance Text [Char] where ...        print as string
  992.  
  993. Other examples might include providing optimized versions of primitives
  994. for particular frequently use operators, or providing a default
  995. behaviour as in:
  996.  
  997.     class Eq a where (==) = error "no definition of equality specified"
  998.  
  999. Haskell requires the context of an overloaded function to be reduced to
  1000. a form where the only predicates that it contains are of the form C a.
  1001. This means that the inferred type of an object may be simplified before
  1002. the full type of that object is known.  For example, we might define a
  1003. function:
  1004.  
  1005.      f x = show [x,x]
  1006.  
  1007. The inferred type in Haskell is f :: Text a => a -> String and the
  1008. decision about which of the two instance declarations above should be
  1009. used has already been forced on us.  To see this, note that f 'a' would
  1010. evaluate to the string "['a', 'a']".  But if we allowed the second
  1011. instance declaration above to be used, show ['a', 'a'] would evaluate
  1012. to "aa".  This breaks a fundamental property of the language where we
  1013. expect to be able to replace one subexpression with another equal term
  1014. and obtain the same result.
  1015.  
  1016. In Gofer, the type system is a little different and the inferred type
  1017. is f :: Text [a] => a -> String.  The decision about which instance
  1018. declaration to use is postponed until the type assigned to 'a' is
  1019. known.  Thus both f 'a' and show ['a', 'a'] evaluate to "aa" without
  1020. any contradiction.
  1021.  
  1022. Although the type system in Gofer has always been able to support the
  1023. use of certain overlapping instance declarations, previous versions of
  1024. the system imposed stronger static restrictions which prohibited their
  1025. use.  Gofer 2.28 relaxes these restrictions by allowing a program to
  1026. contain overlapping instance declarations so long as:
  1027.  
  1028.   o  One of the instance predicates being declared is a substitution
  1029.      instance of the other.  Thus:
  1030.  
  1031.          instance Eq [Char] where ...    -- OK
  1032.          instance Eq a => Eq [a] where ...
  1033.  
  1034.      is permitted because the second predicate, Eq [a], is more general
  1035.      than the first, Eq [Char], which can be obtained by substituting
  1036.      Char for the type variable a.  However, the example at the
  1037.      beginning of this section:
  1038.  
  1039.          instance CX (a,Int) where ...   -- ILLEGAL
  1040.          instance CX (Int,a) where ...
  1041.  
  1042.      is not allowed since neither (a,Int) or (Int,a) is a substitution
  1043.      instance of the other (even though they have a common instance
  1044.      (Int,Int)).
  1045.  
  1046.   o  The two instances declared are not identical.  This rules out
  1047.      examples like:
  1048.  
  1049.          instance Eq Char where ...    -- ILLEGAL
  1050.          instance Eq Char where ...
  1051.  
  1052. The features described here are added principally for experimentation.
  1053. I have some particular applications that I want to try out (which is
  1054. why I actually implemented these ideas) but I would also be very
  1055. interested to hear from anyone else that makes use of this extension.
  1056.  
  1057.  
  1058. .ST 3.3  Parsing Haskell syntax
  1059. ---------------------------
  1060. From correspondence that I have received, quite a few people use Gofer
  1061. to develop programs which, ultimately, will be compiled and executed
  1062. using a Haskell system.  Although the syntax of the two languages is
  1063. quite similar, it has been necessary to comment out module headers and
  1064. other constructs in Haskell programs before they could be used with
  1065. previous version of Gofer.
  1066.  
  1067. The new version of the Gofer system is now able to parse these
  1068. additional constructs (and will generate an error message if a syntax
  1069. error occurs).  However: NO ATTEMPT IS MADE TO INTERPRET OR USE THE
  1070. INFORMATION PROVIDED BY THESE ADDITIONAL CONSTRUCTS.  This feature is
  1071. provided purely for the convenience of those people using Gofer and
  1072. Haskell in the manner described above.  Gofer does not currently
  1073. support any notion of modules beyond the use of separate script files.
  1074.  
  1075. The following changes have been made:
  1076.  
  1077.   o  The identifiers:
  1078.  
  1079.          deriving     default      module      interface
  1080.          import       renaming     hiding      to
  1081.  
  1082.      are now reserved words in Gofer.  Any program that uses one of
  1083.      these as an identifier with an older version of Gofer will need
  1084.      to be modified to use a different name instead.
  1085.  
  1086.   o  Module headers and import declarations may be included in a Gofer
  1087.      program using the syntax set out in version 1.2 of the Haskell
  1088.      report.  Several modules may be included in a single file (but of
  1089.      course, Gofer makes no distinction between the sections of code
  1090.      appearing in different `modules').
  1091.  
  1092.   o  Datatype definitions may include deriving clauses such as:
  1093.  
  1094.          data Maybe a = Just a | Nothing deriving (Eq, Text)
  1095.  
  1096.      although no derived instances will actually be generated.
  1097.      If you need these facilities, you might consider writing out
  1098.      the instances of the type classes concerned yourself in a
  1099.      separate file which can be loaded when you run your program
  1100.      with Gofer, but which are omitted when you compile it with a
  1101.      proper Haskell system.
  1102.  
  1103.   o  Programs may include default declarations, although, once again,
  1104.      these are ignored; for example, there is no restriction on the
  1105.      forms of type that can be included in a default declaration, nor
  1106.      will an error occur if a single module includes multiple default
  1107.      declarations.
  1108.  
  1109.  
  1110. .ST 3.4  Local definitions in comprehensions
  1111. ----------------------------------------
  1112. We all make mistakes.  The syntax for Gofer currently permits a local
  1113. definition to appear in a list comprehension (and indeed, in the monad
  1114. comprehensions described in the next section):
  1115.  
  1116.     [ (x,y) | x <- xs, y = f x, p y ]
  1117.  
  1118. This example is implemented by translating it to something equivalent
  1119. to:
  1120.  
  1121.     map h xs where h []     = []
  1122.                    h (x:xs) = let y = f x
  1123.                               in  if p y then (x,y) : h xs
  1124.                                          else h xs
  1125.  
  1126. It is cumbersome to rewrite this using list comprehensions without
  1127. local definitions:
  1128.  
  1129.     concat [ let y = f x in [ (x,y) | p y ] | x <- xs ]
  1130.  
  1131. so we might resort to the `hack' of writing:
  1132.  
  1133.     [ y | x <- xs, y <- [f x], p y ]
  1134.  
  1135. which works (but doesn't extend to recursive bindings, and is really an
  1136. inappropriate use for a list; a list is used to represent a sequence of
  1137. zero or more objects, so using a list when you know that there is
  1138. always going to be exactly one element seems unnecessary).  So, to
  1139. summarize, I still think that local definitions can be useful in
  1140. comprehensions.
  1141.  
  1142. So where is the mistake I mentioned?  The problem is with the SYNTAX.
  1143. First, it is rather easy to confuse the comprehension above with the
  1144. comprehension:
  1145.  
  1146.     [ (x,y) | x <- xs, y == f x, p y ],
  1147.  
  1148. leading to errors which are hard to detect.  The second is that the
  1149. syntax is too restrictive; you can only give relatively simple local
  1150. declarations -- mutually recursive definitions and function bindings
  1151. are not permitted.
  1152.  
  1153. Gofer 2.28 now supports a new syntax for local definitions in
  1154. comprehensions.  The old syntax is still supported, for compatibility
  1155. with previous releases, but will be deleted in the next public release
  1156. (assuming I remember).  Local declarations can now be included in a
  1157. comprehension using a qualifier of the form let { decls }.  So the
  1158. comprehension at the beginning of this section can also be written:
  1159.  
  1160.     [ (x,y) | x <- xs, let {y = f x}, p y ]
  1161.  
  1162. Note that the braces cannot usually be omitted in Gofer due to an
  1163. undocumented extension to the syntax of Gofer function declarations.
  1164. The braces would not be needed if this syntax were added to a standard
  1165. Haskell system.
  1166.  
  1167. This extension means that it is now possible to write comprehensions
  1168. such as:
  1169.  
  1170.     [ (x,y,z) | x <- xs, let { y   = f x z;
  1171.                                z   = g x y;
  1172.                                f n = h n [] }, p x y z ]
  1173.      
  1174. Once again, this is still an experimental feature.  I suspect it will
  1175. be of most use to anyone making substantial use of monad comprehensions
  1176. as described in the next section.
  1177.  
  1178.  
  1179. .co-------------------------------------------------------------------|
  1180. .ST 4. CONSTRUCTOR CLASSES
  1181.  
  1182. [This is a long section; if you are not interested in experimenting
  1183. with Gofer's system of constructor classes, you can skip straight ahead
  1184. to the next section without missing anything.  Of course, if you don't
  1185. know what a constructor class is, you might want to read at least some
  1186. of this section before you can make that decision.]
  1187.  
  1188. One of the biggest changes in Gofer version 2.28 is the provision of
  1189. support for constructor classes.  This section provides an overview of
  1190. constructor classes which should hopefully, in conjunction with the
  1191. example supplied with the full distribution, be enough to get you
  1192. started.  More technical details about constructor classes can be
  1193. obtained by contacting me.
  1194.  
  1195. Some of the following introduction here (particularly sections 4.1 and
  1196. 4.2) may seem somewhat familiar to those of you have already read one
  1197. of the papers that I have written on the subject although I have added
  1198. some more information about the Gofer implementation.
  1199.  
  1200. Others may find that this section of the documentation seems rather
  1201. technical; try not to be put off at first sight.  Looking through the
  1202. examples and the documentation, you may find it is easier to understand
  1203. than you expect!
  1204.  
  1205. A final comment before starting: there is, as yet, no strong consensus
  1206. on the names and syntax that would be best for monad operations,
  1207. comprehensions etc.  If you have any opinions, or proposals which
  1208. differ from what you see here, please let me know ... I'd be very
  1209. interested to hear other people's opinions on this.
  1210.  
  1211.  
  1212. .ST 4.1  An overloaded map function
  1213. -------------------------------
  1214. Many functional programs use the map function to apply a function to
  1215. each of the elements in a given list.  The type and definition of this
  1216. function as given in the Gofer standard prelude are as follows:
  1217.  
  1218.     map          ::  (a -> b) -> ([a] -> [b])
  1219.     map f []      =  []
  1220.     map f (x:xs)  =  f x : map f xs
  1221.  
  1222. It is well known that the map function satisfies the familiar laws:
  1223.  
  1224.     map id         = id
  1225.     map f . map g  =  map (f . g)
  1226.  
  1227. A category theorist will recognize these observations as indicating
  1228. that there is a functor from types to types whose object part maps any
  1229. given type a to the list type [a] and whose arrow part maps each
  1230. function f::a -> b to the function map f :: [a] -> [b].  A functional
  1231. programmer will recognize that similar constructions are also used with
  1232. a wide range of other data types, as illustrated by the following
  1233. examples:
  1234.  
  1235.     data Tree a  =  Leaf a  |  Tree a :^: Tree a
  1236.  
  1237.     mapTree            :: (a -> b) -> (Tree a -> Tree b)
  1238.     mapTree f (Leaf x)  = Leaf (f x)
  1239.     mapTree f (l :^: r) = mapTree f l :^: mapTree f r
  1240.  
  1241.     data Maybe a =  Just a  |  Nothing
  1242.  
  1243.     mapMaybe           :: (a -> b) -> (Maybe a -> Maybe b)
  1244.     mapMaybe f (Just x) = Just (f x)
  1245.     mapMaybe f Nothing  = Nothing
  1246.  
  1247. Each of these functions has a similar type to that of the original map
  1248. and also satisfies the functor laws given above.  With this in mind, it
  1249. seems a shame that we have to use different names for each of these
  1250. variants.
  1251.  
  1252. A more attractive solution would allow the use of a single name map,
  1253. relying on the types of the objects involved to determine which
  1254. particular version of the map function is required in a given
  1255. situation.  For example, it is clear that map (1+) [1,2,3] should be
  1256. a list, calculated using the original map function on lists, while
  1257. map (1+) (Just 1) should evaluate to Just 2 using mapMaybe.
  1258.  
  1259. Unfortunately, in a language using standard Hindley/Milner type
  1260. inference, there is no way to assign a type to the map function that
  1261. would allow it to be used in this way.  Furthermore, even if typing
  1262. were not an issue, use of the map function would be rather limited
  1263. unless some additional mechanism was provided to allow the definition
  1264. to be extended to include new datatypes perhaps distributed across a
  1265. number of distinct program files.
  1266.  
  1267.  
  1268. .ST 4.1.1  An attempt to define map using type classes
  1269. --------------------------------------------------
  1270. The ability to use a single function symbol with an interpretation that
  1271. depends on the type of its arguments is commonly known as overloading.
  1272. In Gofer, overloading is implemented using type classes -- which can be
  1273. thought of as sets of types.  For example, the Eq class defined by:
  1274.  
  1275.     class Eq a where
  1276.         (==), (/=) :: a -> a -> Bool
  1277.  
  1278. (together with an appropriate set of instance declarations) is used to
  1279. describe the set of types whose elements can be compared for equality.
  1280. The standard prelude for Gofer includes integers, floating point
  1281. numbers, characters, booleans, lists (in which the type of the members
  1282. is also in Eq) and so forth.  There is no need for all the definitions
  1283. of equality to be combined in a single script file; new definitions of
  1284. equality are typically included each time a new datatype is defined.
  1285.  
  1286. Functions such as nub, defined in the standard prelude as:
  1287.  
  1288.     nub       :: Eq a => [a] -> [a]   -- remove duplicates from list
  1289.     nub []     = []
  1290.     nub (x:xs) = x : nub (filter (x/=) xs)
  1291.  
  1292. can be used with any choice of type for the type variable a so long as
  1293. it is an instance of Eq.  Only a single definition of the nub function
  1294. is required.
  1295.  
  1296. Unfortunately, the system of type classes is not sufficiently powerful
  1297. to give a satisfactory treatment for the map function; to do so would
  1298. require a class Map and a type expression m(t) involving the type
  1299. variable t such that S = { m(t) | t is a member of Map } includes (at
  1300. least) the types:
  1301.  
  1302.     { (a -> b) -> ([a] -> [b]),
  1303.       (a -> b) -> (Tree a -> Tree b),
  1304.       (a -> b) -> (Maybe a -> Maybe b), ....
  1305.                                     | a and b arbitrary types }
  1306.  
  1307. .cc 5
  1308. The only possibility is to take m(t) = t and choose Map as the set of
  1309. types S for which the map function is required:
  1310.  
  1311.     class Map t where map :: t
  1312.  
  1313.     instance Map ((a -> b) -> ([a] -> [b])) where ...
  1314.     instance Map ((a -> b) -> (Tree a -> Tree b)) where ...
  1315.     instance Map ((a -> b) -> (Maybe a -> Maybe b)) where ...
  1316.  
  1317. This syntax is permitted in Gofer (but not in Haskell) but it does not
  1318. give a sufficiently accurate characterization of the type of map to be
  1319. of much use.  For example, the principal type of \i j -> map j . map i
  1320. is:
  1321.  
  1322.     (Map (a -> c -> e), Map (b -> e -> d)) => a -> b -> c -> d
  1323.  
  1324. (a and b are the types of i and j respectively).  This is complicated
  1325. and does not enforce the condition that i and j have function types.
  1326. Furthermore, the type is ambiguous (the type variable e does not appear
  1327. to the right of the => symbol or in the assumptions).  Under these
  1328. conditions, we cannot guarantee a well-defined semantics for this
  1329. expression.  Other attempts to define the map function, for example
  1330. using multiple parameter type classes, have also failed for essentially
  1331. the same reasons.
  1332.  
  1333.  
  1334. .ST 4.1.2  A solution using constructor classes
  1335. -------------------------------------------
  1336. A much better approach is to notice that each of the types for which
  1337. the map function is required is of the form:
  1338.  
  1339.     (a -> b) -> (f a -> f b).
  1340.  
  1341. The variables a and b here represent arbitrary types while f ranges
  1342. over the set of type constructors for which a suitable map function has
  1343. been defined.  In particular, we would expect to include the list
  1344. constructor (which we write as [] in Gofer), Tree and Maybe as elements
  1345. of this set.  Motivated by our earlier comments we will call this set
  1346. Functor.  With only a small extension to the Gofer syntax for type
  1347. classes this can be described by:
  1348.  
  1349.     class Functor f where
  1350.         map :: (a -> b) -> (f a -> f b)
  1351.  
  1352.     instance Functor [] where
  1353.         map f []        = []
  1354.         map f (x:xs)    = f x : map f xs
  1355.  
  1356.     instance Functor Tree where
  1357.         map f (Leaf a)  = Leaf (f a)
  1358.         map f (l :^: r) = map f l :^: map f r
  1359.  
  1360.     instance Functor Maybe where
  1361.         map f (Just x) = Just (f x)
  1362.         map f Nothing  = Nothing
  1363.  
  1364. .cc 5
  1365. Functor is our first example of a constructor class.  The following
  1366. extract illustrates how the definitions for Functor work in practice:
  1367.  
  1368.     ? map (1+) [1,2,3]
  1369.     [2, 3, 4]
  1370.     (15 reductions, 44 cells)
  1371.     ? map (1+) (Leaf 1 :^: Leaf 2)
  1372.     Leaf 2 :^: Leaf 3
  1373.     (10 reductions, 46 cells)
  1374.     ? map (1+) (Just 1)
  1375.     Just 2
  1376.     (4 reductions, 17 cells)
  1377.     ?
  1378.  
  1379. Furthermore, by specifying the type of map function more precisely,
  1380. we avoid the ambiguity problems mentioned above.  For example, the
  1381. principal type of \i j -> map j . map i is simply:
  1382.  
  1383.     Functor f => (a -> b) -> (b -> c) -> f a -> f c
  1384.  
  1385. which is not ambiguous, and makes the types of i and j as (a -> b)
  1386. and (b -> c) respectively.
  1387.  
  1388. [You can try these examples yourself using the Gofer system.  The first
  1389. thing you need to do is start Gofer using the file cc.prelude instead
  1390. of the usual Gofer standard.prelude.  The cc.prelude includes the
  1391. definition of the functor class and the instance for Functor [].  The
  1392. remaining two instance declarations are included (along with lots of
  1393. other examples) in the file ccexamples.gs in the demos/Ccexamples
  1394. subdirectory of the standard distribution.]
  1395.  
  1396.  
  1397. .ST 4.1.3  The kind system
  1398. ----------------------
  1399. Each instance of Functor can be thought of as a function from types to
  1400. types.  It would be nonsense to allow the type Int of integers to be an
  1401. instance of Functor, since the type (a -> b) ->(Int a -> Int b) is
  1402. obviously not well-formed.  To avoid unwanted cases like this, we have
  1403. to ensure that all of the elements in any given class are of the same
  1404. kind.
  1405.  
  1406. To do this, we formalize the notion of kind, writing * for the kind of
  1407. all types and k1 -> k2 for the kind of a constructor which takes
  1408. something of kind k1 and returns something of kind k2.  This notion
  1409. comes is motivated by some theoretical work by Henk Barendregt on the
  1410. subject of `Generalized type systems'; Do not confuse this with the use
  1411. of the symbol * in a certain well-known functional language where it
  1412. represents a type variable.  These things are completely different!
  1413.  
  1414. Rather than thinking only of types we work with constructors which
  1415. include types as a special case.  Constructors take the form:
  1416.  
  1417.     Constructor  ::=  ConstructorConstant
  1418.                   |   Constructor1 Constructor2
  1419.                   |   variable
  1420.  
  1421. This corresponds very closely to the way that most type expressions
  1422. are already written in Gofer.  For example, Tree a is an application
  1423. of the constructor constant Tree to the variable a.  Gofer has some
  1424. special syntax for tuple, list and function types.  The corresponding
  1425. constructors can also be written directly in Gofer.  For example:
  1426.  
  1427.     a -> b   =  (->) a b
  1428.     [a]      =  [] a
  1429.     (a,b)    =  (,) a b
  1430.     (a,b,c)  =  (,,) a b c
  1431.     etc ...
  1432.  
  1433. Each constructor constant has a corresponding kind.  For example:
  1434.  
  1435.     Int, Float, ()    ::  *
  1436.     [], Tree, Maybe   ::  * -> *
  1437.     (->), (,)         ::  * -> * -> *
  1438.     (,,)              ::  * -> * -> * -> *
  1439.  
  1440. Applying one constructor C :: k1 -> k2 to a construct C' :: k1 gives
  1441. a constructor expression C C' with kind k2.  Notice that this is just
  1442. the same sort of thing you would expect from applying a function of
  1443. type a -> b to an value of type b; kinds really are very much like
  1444. `types for constructors'.
  1445.  
  1446. Instead of checking that type expressions contain the correct number of
  1447. arguments for each type constructor, we need to check that any type
  1448. expression has kind *.  In a similar way, all of the elements of a
  1449. constructor class must have the same kind; for example, a constructor
  1450. class constraint of the form Functor f is only valid if f is a
  1451. constructor expression of kind * -> *.  Note also that our system
  1452. includes Gofer/Haskell type classes as a special case; a type class is
  1453. simply a constructor class for which each instance has kind *.  Multiple
  1454. parameter classes can also be dealt with in the same way, using a tuple
  1455. of kinds (k1,...,kn) to indicate the kind of constructors required for
  1456. each argument.
  1457.  
  1458. The language of constructors is essentially a system of combinators
  1459. without any reduction rules.  As such, standard techniques can be
  1460. used to infer the kinds of constructor variables, constructor constants
  1461. introduced by new datatype definitions and the kind of the elements
  1462. held in any particular constructor class.  The important point is that
  1463. there is no need -- and indeed, in our current implementation, no
  1464. opportunity -- for the programmer to supply kind information
  1465. explicitly.  We regard this as a significant advantage since it means
  1466. that the programmer can avoid much of the complexity that might
  1467. otherwise result from the need to annotate type expressions with
  1468. kinds.
  1469.  
  1470.  
  1471. .ST 4.2  Monads as an application of constructor classes
  1472. ----------------------------------------------------
  1473. Motivated by the work of Moggi and Spivey, Wadler has proposed a style
  1474. of functional programming based on the use of monads.  While the theory
  1475. of monads had already been widely studied in the context of abstract
  1476. category theory, Wadler introduced the idea that monads could be used
  1477. as a practical method for modeling so-called `impure' features in a
  1478. purely functional programming language.
  1479.  
  1480. The examples in this and following sections illustrate that the use of
  1481. constructor classes can be particularly convenient for programming in
  1482. this style.  You will also find a lot more examples prepared for use
  1483. with Gofer in the file ccexamples in the demos/Ccexamples subdirectory
  1484. of the standard distribution.
  1485.  
  1486.  
  1487. .ST 4.2.1  A framework for programming with monads
  1488. ----------------------------------------------
  1489. The basic motivation for the use of monads is the need to distinguish
  1490. between computations and the values that they produce.  If m is a monad
  1491. then an object of type (m a) represents a computation which is expected
  1492. to produce a value of type a.  These types reflect the fact that the
  1493. use of particular programming language features in a given calculation
  1494. is a property of the computation itself and not of the result that it
  1495. produces.
  1496.  
  1497. Taking the approach outlined by Wadler in his paper `The Essence of
  1498. Functional Programming' (POPL '92), we introduce a constructor class of
  1499. monads using the definition:
  1500.  
  1501.     class Functor m => Monad m where
  1502.         result    :: a -> m a
  1503.         join      :: m (m a) -> m a
  1504.         bind      :: m a -> (a -> m b) -> m b
  1505.  
  1506.         join x     = bind x id
  1507.         x `bind` f = join (map f x)
  1508.  
  1509. The expression Functor m => Monad m defines Monad as a subclass of
  1510. Functor ensuring that, for any given monad, there will also be a
  1511. corresponding instance of the overloaded map function.  The use of a
  1512. hierarchy of classes enables us to capture the fact that not every
  1513. instance of Functor can be treated as an instance of Monad in any
  1514. natural way.
  1515.  
  1516. [If you are familiar with either my previous papers or Wadler's
  1517. writings on the use of monads, you might notice that the declaration
  1518. above uses the name `result' in place of `return' or `unit' that have
  1519. been previously used for the same thing.  The latter two choices have
  1520. been used elsewhere for rather different purposes, and there is
  1521. currently no clear picture of which names should be used.  The
  1522. identifier `result' is the latest in a long line of attempts to find a
  1523. name which both conveys the appropriate meaning and is not already in
  1524. use for other applications.]
  1525.  
  1526. By including default definitions for bind and join we only need to give
  1527. a definition for one of these (in addition to a definition for result)
  1528. to completely define an instance of Monad.  This is often quite
  1529. convenient.  On the other hand, it would be an error to omit
  1530. definitions for both operators since the default definitions are
  1531. clearly circular.  We should also mention that the member functions in
  1532. an instance of Monad are expected to satisfy a number of laws which are
  1533. not reflected in the class definition above.
  1534.  
  1535. The following declaration defines the standard monad structure for the
  1536. list constructor [] which can be used to describe computations
  1537. producing multiple results, corresponding to a simple form of
  1538. non-determinism:
  1539.  
  1540.     instance Monad [] where
  1541.         result x        = [x]
  1542.         []     `bind` f = []
  1543.         (x:xs) `bind` f = f x ++ (xs `bind` f)
  1544.  
  1545. As a second example, the monad structure for the Maybe datatype, which
  1546. might be used to describe computations which fail to produce any value
  1547. at all if an error condition occurs, can be described by:
  1548.  
  1549.     instance Monad Maybe where
  1550.         result x         = Just x
  1551.         Just x  `bind` f = f x
  1552.         Nothing `bind` f = Nothing
  1553.  
  1554. Another interesting use of monads is to model programs that make use of
  1555. an internal state.  Computations of this kind can be represented by
  1556. functions of type s-> (a,s) (often referred to as state transformers)
  1557. mapping an initial state to a pair containing the result and final
  1558. state.  In order to get this into the appropriate form for the Gofer
  1559. system of constructor classes, we introduce a new datatype:
  1560.  
  1561.     data State s a = ST (s -> (a,s))
  1562.  
  1563. The functor and monad structures for state transformers are as follows:
  1564.  
  1565.     instance Functor (State s) where
  1566.         map f (ST st) = ST (\s -> let (x,s') = st s in (f x, s'))
  1567.  
  1568.     instance Monad (State s) where
  1569.         result x      = ST (\s -> (x,s))
  1570.         ST m `bind` f = ST (\s -> let (x,s') = m s
  1571.                                       ST f'  = f x
  1572.                                   in  f' s')
  1573.  
  1574. Notice that the State constructor has kind * -> * -> * and that the
  1575. declarations above define State s as a monad and functor for any state
  1576. type s (and hence State s has kind * -> * as required for an instance
  1577. of these classes).  There is no need to assume a fixed state type.
  1578.  
  1579. From a user's point of view, the most interesting properties of a monad
  1580. are described, not by the result, bind and join operators, but by the
  1581. additional operations that it supports.  The following examples are
  1582. often useful when working with state monads.  The first can be used to
  1583. `run' a program given an initial state and discarding the final state,
  1584. while the second might be used to implement an integer counter in a
  1585. State Int monad:
  1586.  
  1587.     startingWith          :: State s a -> s -> a
  1588.     ST m `startingWith` s0 = result where (result,_) = m s0
  1589.  
  1590.     incr :: State Int Int
  1591.     incr  = ST (\s -> (s,s+1))
  1592.  
  1593. To illustrate the use of state monads, consider the task of labeling
  1594. each of the nodes in a binary tree with distinct integer values.  One
  1595. simple definition is:
  1596.  
  1597.     label     :: Tree a -> Tree (a,Int)
  1598.     label tree = fst (lab tree 0)
  1599.      where lab (Leaf n)  c  =  (Leaf (n,c), c+1)
  1600.            lab (l :^: r) c  =  (l' :^: r', c'')
  1601.                                where (l',c')  = lab l c
  1602.                                      (r',c'') = lab r c'
  1603.  
  1604. This uses an explicit counter (represented by the second parameter to
  1605. lab) and great care must be taken to ensure that the appropriate
  1606. counter value is used in each part of the program; simple errors, such
  1607. as writing c in place of c' in the last line, are easily made but can
  1608. be hard to detect.
  1609.  
  1610. An alternative definition, using a state monad and following the
  1611. layout suggested in Wadler's POPL paper, can be written as follows:
  1612.  
  1613.     label     :: Tree a -> Tree (a,Int)
  1614.     label tree = lab tree `startingWith` 0
  1615.      where lab (Leaf n)  = incr                  `bind` \c ->
  1616.                            result (Leaf (n,c))
  1617.            lab (l :^: r) = lab l                 `bind` \l' ->
  1618.                            lab r                 `bind` \r' ->
  1619.                            result (l' :^: r')
  1620.  
  1621. While this program is perhaps a little longer than the previous
  1622. version, the use of monad operations ensures that the correct counter
  1623. value is passed from one part of the program to the next.  There is no
  1624. need to mention explicitly that a state monad is required: The use of
  1625. startingWith and the initial value 0 (or indeed, the use of incr on its
  1626. own) are sufficient to determine the monad State Int needed for the
  1627. bind and result operators.  It is not necessary to distinguish between
  1628. different versions of the monad operators bind, result and join or to
  1629. rely on explicit type declarations.
  1630.  
  1631.  
  1632. .ST 4.2.2  Monad comprehensions
  1633. ---------------------------
  1634. Several functional programming languages provide support for list
  1635. comprehensions, enabling some common forms of computation with lists to
  1636. be written in a concise form resembling the standard syntax for set
  1637. comprehensions in mathematics.  In his paper `Comprehending Monads'
  1638. (ACM Lisp and Functional Programming, 1990), Wadler made the
  1639. observation that the comprehension notation can be generalized to
  1640. arbitrary monads, of which the list constructor is just one special
  1641. case.
  1642.  
  1643. In Wadler's notation, a monad comprehension is written using the syntax
  1644. of a list comprehension but with a superscript to indicate the monad in
  1645. which the comprehension is to be interpreted.  This is a little awkward
  1646. and makes the notation less powerful than might be hoped since each
  1647. comprehension is restricted to a particular monad.  Using the
  1648. overloaded operators described in the previous section, Gofer provides
  1649. a more flexible form of monad comprehension which relies on overloading
  1650. rather than superscripts.  At the time of writing, this is the only
  1651. concrete implementation of monad comprehensions known to us.
  1652.  
  1653. In our system, a monad comprehension is an expression of the form
  1654. [e | qs ] where e is an expression and gs is a list of generators of
  1655. the form p <- exp.  As a special case, if gs is empty then the
  1656. comprehension [ e | qs ] is written as [ e ].  The implementation of
  1657. monad comprehensions is based on the following translation of the
  1658. comprehension notation in terms of the result and bind operators
  1659. described in the previous section:
  1660.  
  1661.     [ e ]                = result e
  1662.     [ e | p <- exp, qs ] = exp `bind` \p -> [ e | qs ]
  1663.  
  1664. In this notation, the label function from the previous section can
  1665. be rewritten as:
  1666.  
  1667.     label     :: Tree a -> Tree (a,Int)
  1668.     label tree = lab tree `startingWith` 0
  1669.      where lab (Leaf n)  = [ Leaf (n,c) | c <- incr ]
  1670.            lab (l :^: r) = [  l :^: r   | l <- lab l, r <- lab r ]
  1671.  
  1672. Applying the translation rules for monad comprehensions to this
  1673. definition yields the previous definition in terms of result and bind.
  1674. The principal advantage of the comprehension syntax is that it is often
  1675. more concise and, in the author's opinion, sometimes more attractive.
  1676.  
  1677.  
  1678. .ST 4.2.3  Monads with a zero
  1679. -------------------------
  1680. Assuming that you are familiar with Gofer's list comprehensions, you
  1681. will know that it is also possible to include boolean guards in
  1682. addition to generators in the definition of a list comprehension.  Once
  1683. again, Wadler showed that this was also possible in the more general
  1684. setting of monad comprehensions, so long as we restrict such
  1685. comprehensions to monads that include a special element zero satisfying
  1686. a small number of laws.  This can be dealt with in our framework by
  1687. defining a subclass of Monad:
  1688.  
  1689.     class Monad m => Monad0 m where
  1690.         zero   :: m a
  1691.  
  1692. For example, the List monad has the empty list as a zero element:
  1693.  
  1694.     instance Monad0 [] where zero = []
  1695.  
  1696. Note that not there are also some monads which do not have a zero
  1697. element and hence cannot be defined as instances of Monad0.  The
  1698. State s monads described in Section 4.2.1 are a simple example of
  1699. this.
  1700.  
  1701. Working in a monad with a zero, a comprehension involving a boolean
  1702. guard can be implemented using the translation:
  1703.  
  1704.     [ e | guard, qs ]  =  if guard then [ e | qs ] else zero
  1705.  
  1706. Notice that, as far as the type system is concerned, the use of
  1707. zero in the translation of a comprehension involving a guard automatically
  1708. captures the restriction to monads with a zero:
  1709.  
  1710.     ? :t \x p -> [ x | p x ]
  1711.     \x p -> [ x | p x ] :: Monad0 b => a -> (a -> Bool) -> b a
  1712.     ?
  1713.  
  1714. The inclusion of a zero element also allows a slightly different
  1715. translation for generators in comprehensions:
  1716.  
  1717.     [ e | p <- exp, qs ]  =  exp `bind` f
  1718.                              where  f p  =  [ e | qs ]
  1719.                                     f _  =  zero
  1720.  
  1721. This corresponds directly to the semantics of standard Gofer list
  1722. comprehensions, but only differs from the semantics of the translation
  1723. given in the previous section when p is an irrefutable pattern; i.e.
  1724. when p is a pattern which may not match the value (or values) generated
  1725. by exp.  You can see the difference by trying the following example
  1726. in Gofer:
  1727.  
  1728.     ? [ x | [x] <- [[1],[],[2]]]
  1729.     [1, 2]
  1730.     (9 reductions, 31 cells)
  1731.     ? map (\[x] -> x) [[1],[],[2]]
  1732.     [1, 
  1733.     Program error: {v157 []}
  1734.     (8 reductions, 66 cells)
  1735.  
  1736.     ?
  1737.  
  1738. In order to retain compatibility with the standard list comprehension
  1739. notation, Gofer always uses the second translation above for generators
  1740. if the pattern p is refutable.  This may sometimes give inferred types
  1741. which are more restrictive than you expect.  For example, tuples are
  1742. not irrefutable patterns in Gofer or Haskell, and so the function:
  1743.  
  1744.     ? :t \xs -> [ x | (x,y) <- xs ]
  1745.     \xs -> [ x | (x,y)<-xs ] :: Monad0 a => a (b,c) -> a b
  1746.     ?
  1747.  
  1748. is restricted to monads with a zero because the expanded translation
  1749. above is used.  You can always avoid this problem by using the lazy
  1750. pattern construct (i.e. the tilde operator, ~p) as in:
  1751.  
  1752.     ? :t \xs -> [ x | ~(x,y) <- xs ]
  1753.     \xs -> [ x | ~(x,y)<-xs ] :: Monad a => a (b,c) -> a b
  1754.     ?
  1755.  
  1756. [At one stage, I was using a different form of brackets to represent
  1757. monad comprehensions, implemented using the original translation to
  1758. avoid changing the semantics of list comprehensions.  But I finally
  1759. decided that it would be better to use standard comprehension notation
  1760. with lazy pattern annotations where necessary since this is less
  1761. cumbersome than writing \xs -> [| x | (x,y) <- xs |] in place of the
  1762. comprehension above.  Please let me know what you think!]
  1763.  
  1764.  
  1765. .ST 4.2.4  Generic operations on monads
  1766. -----------------------------------
  1767. The combination of polymorphism and constructor classes in our system
  1768. makes it possible to define generic functions which can be used on a
  1769. wide range of different monads.  A simple example of this is the
  1770. `Kleisli composition' for an arbitrary monad, similar to the usual
  1771. composition of functions except that it also takes care of `side
  1772. effects'.  The general definition is as follows:
  1773.  
  1774.    (@@)   :: Monad m => (a -> m b) -> (c -> m a) -> (c -> m b)
  1775.    f @@ g  = join . map f . g
  1776.  
  1777. For example, in a monad of the form State s, the expression f @@ g
  1778. denotes a state transformer in which the final state of the computation
  1779. associated with g is used as the initial state for the computation
  1780. associated with f.  More precisely, for this particular kind of monad,
  1781. the general definition given above is equivalent to:
  1782.  
  1783.     (@@)  :: (b -> State s c) -> (a -> State s b) -> (a -> State s c)
  1784.     f @@ g = \a -> STM (\s0 -> let ST g'  = g a
  1785.                                    (b,s1) = g' s0
  1786.                                    ST f'  = f b
  1787.                                    (c,s2) = f' s1
  1788.                                in  (c,s2))
  1789.  
  1790. The biggest advantage of the generic definition is that there is no
  1791. need to construct new definitions of (@@) for every different monad.
  1792. On the other hand, if specific definitions were required for some
  1793. instances, perhaps in the interests of efficiency, we could simply
  1794. include (@@) as a member function of Monad and use the generic
  1795. definition as a default implementation.
  1796.  
  1797. Generic operations can also be defined using the comprehension
  1798. notation:
  1799.  
  1800.     mapl             :: Monad m => (a -> m b) -> ([a] -> m [b])
  1801.     mapl f []         = [ [] ]
  1802.     mapl f (x:xs)     = [ y:ys | y <- f x, ys <- mapl f xs ]
  1803.  
  1804. This is the same as mapping a function down the elements of a list
  1805. using the normal map function except that, in the presence of side
  1806. effects, the order in which the applications are carried out is
  1807. important.  For mapl, we start on the left (i.e. the front of the list)
  1808. and work towards the right.  There is a corresponding dual which works
  1809. in the reverse direction:
  1810.  
  1811.     mapr             :: Monad m => (a -> m b) -> ([a] -> m [b])
  1812.     mapr f []         = [ [] ]
  1813.     mapr f (x:xs)     = [ y:ys | ys <- mapr f xs, y <- f x ]
  1814.  
  1815. These general functions have applications in several kinds of monad
  1816. with examples involving state and output.
  1817.  
  1818. The comprehension notation can also be used to define a generalization
  1819. of Haskell's filter function which works in an arbitrary monad with a
  1820. zero:
  1821.  
  1822.     filter           :: Monad0 m => (a -> Bool) -> m a -> m a
  1823.     filter p xs       = [ x | x<-xs, p x ]
  1824.  
  1825. There are many other general purpose functions that can be defined
  1826. in the current framework and used in arbitrary monads.  To give you
  1827. some further examples, here are generalized versions of the foldl and
  1828. foldr functions which work in an arbitrary monad:
  1829.  
  1830.     mfoldl           :: Monad m => (a -> b -> m a) -> a -> [b] -> m a
  1831.     mfoldl f a []     = result a
  1832.     mfoldl f a (x:xs) = f a x `bind` (\fax -> mfoldl f fax xs)
  1833.  
  1834.     mfoldr           :: Monad m => (a -> b -> m b) -> b -> [a] -> m b
  1835.     mfoldr f a []     = result a
  1836.     mfoldr f a (x:xs) = mfoldr f a xs `bind` (\y -> f x y)
  1837.  
  1838. [Generalizing these definitions (and those of mapl, mapr) to work with
  1839. a second arbitrary monad (in place of the list monad) is left as an
  1840. entertaining exercise for the reader :-)]
  1841.  
  1842. As a final example, here is a definition of a `while' loop for an
  1843. arbitrary monad:
  1844.  
  1845.     while    :: Monad m => m Bool -> m b -> m ()
  1846.     while c s = c  `bind` \b ->
  1847.                 if b then s         `bind` \x ->
  1848.                           while c s
  1849.                      else result ()
  1850.  
  1851.  
  1852. .ST 4.2.5  A family of state monads
  1853. -------------------------------
  1854. We have already described the use of monads to model programs with
  1855. state using the State datatype in Section 4.2.1.  The essential
  1856. property of any such monad is the ability to update the state and we
  1857. might therefore consider a more general class of state monads given by:
  1858.  
  1859.     class Monad (m s) => StateMonad m s where
  1860.         update :: (s -> s) -> m s s
  1861.         set    :: s -> m s s
  1862.         fetch  :: m s s
  1863.         set new = update (\old -> new)
  1864.         fetch   = update id
  1865.  
  1866. An expression of the form update f denotes the computation which
  1867. updates the state using f and result the old state as its result.  For
  1868. example, the incr function described above can be defined as:
  1869.  
  1870.     incr :: StateMonad m Int => m Int Int
  1871.     incr  = update (1+)
  1872.  
  1873. in this more general setting.  The class declaration above also
  1874. includes set and fetch functions which set the state to a particular
  1875. value or return its value.  These are easily defined in terms of the
  1876. update function as illustrated by the default definitions.
  1877.  
  1878. The StateMonad class has two parameters; the first should be a
  1879. constructor of kind (* -> * -> *) while the second gives the state
  1880. type (of kind *); both are needed to specify the type of update.
  1881. The implementation of update for a monad of the form State s is
  1882. straightforward and provides us with our first instance of the
  1883. StateMonad class:
  1884.  
  1885.     instance StateMonad State s where
  1886.         update f = ST (\s -> (s, f s))
  1887.  
  1888. A rather more interesting family of state monads can be described using
  1889. the following datatype definition:
  1890.  
  1891.     data STM m s a = STM (s -> m (a,s)) -- a more sophisticated example,
  1892.                                         -- where the state monad is
  1893.                                         -- parameterized by a second,
  1894.                                         -- arbitrary monad.
  1895.  
  1896. Note that the first parameter to StateM has kind (* -> *), a
  1897. significant extension from Haskell (and previous versions of Gofer)
  1898. where all of the arguments to a type constructor must be types.  This
  1899. is another benefit of the kind system.
  1900.  
  1901. The functor and monad structure of a StateM m s constructor are given
  1902. by:
  1903.  
  1904.     instance Monad m => Functor (STM m s) where
  1905.         map f (STM xs) = STM (\s -> [ (f x, s') | ~(x,s') <- xs s ])
  1906.  
  1907.     instance Monad m => Monad (STM m s) where
  1908.         result x        = STM (\s -> result (x,s))
  1909.         STM xs `bind` f = STM (\s -> xs s `bind` (\(x,s') ->
  1910.                                      let STM f' = f x
  1911.                                      in  f' s'))
  1912.  
  1913. Note the condition that m is an instance of Monad in each of these
  1914. definitions.  If we hadn't used the lazy pattern construct ~(x,s') in
  1915. the instance of Functor, it would have been necessary to strengthen
  1916. this further to instances of Monad0 -- i.e. monads with a zero.
  1917.  
  1918. The definition of StateM m as an instance of StateMonad is also
  1919. straightforward:
  1920.  
  1921.     instance StateMonad (STM m) s where
  1922.         update f = STM (\s -> result (s, f s))
  1923.  
  1924. The following two functions are also useful for work with STM m s
  1925. monads.  The first, protect, allows an arbitrary computation to be
  1926. embedded in a state based computation without access to the state.
  1927. The second, execute, is similar to the startingWith function in
  1928. Section 4.2.1, running a state based computation with a given initial
  1929. state and returning a computation as the result.
  1930.  
  1931. protect          :: Monad m => m a -> STM m s a
  1932. protect m         = STM (\s -> [ (x,s) | x<-m ])
  1933.  
  1934. execute          :: Monad m => s -> STM m s a -> m a
  1935. execute s (STM f) = [ x | ~(x,s') <- f s ]
  1936.  
  1937. Support for monads like StateM m s seems to be an important step
  1938. towards solving the problem of constructing monads by combining
  1939. features from simpler monads, in this case combining the use of state
  1940. with the features of an arbitrary monad m.  I hope that the system of
  1941. constructor classes in Gofer will be a useful tool for people working
  1942. in this area.
  1943.  
  1944.  
  1945. .ST 4.2.6  Monads and substitution
  1946. ------------------------------
  1947. The previous sections have concentrated on the use of monads to
  1948. describe computations.  Monads also have a useful interpretation as a
  1949. general approach to substitution.  This in turn provides another
  1950. application for constructor classes.
  1951.  
  1952. Taking a fairly general approach, a substitution can be considered as a
  1953. function s::v-> t w where the types v and w
  1954. represent sets of variables and the type t a represents a set
  1955. of terms, typically involving elements of type a.  If t is
  1956. a monad and x::t v, then x `bind` s gives the result of
  1957. applying the substitution s to the term x by replacing
  1958. each occurrence of a variable v in x with the corresponding
  1959. term s v in the result.  For example:
  1960.  
  1961.     instance Monad Tree where
  1962.         result             = Leaf
  1963.         Leaf x    `bind` f = f x
  1964.         (l :^: r) `bind` f = (l `bind` f) :^: (r `bind` f)
  1965.  
  1966. With this interpretation in mind, the Kleisli composition (@@) in
  1967. Section 4.2.4 is just the standard way of composing substitutions,
  1968. while the result function corresponds to a null substitution.  The fact
  1969. that (@@) is associative with result as both a left and right identity
  1970. follows from the standard algebraic properties of a monad.
  1971.  
  1972.  
  1973. .ST 4.3  Constructor classes in Gofer
  1974. ---------------------------------
  1975. The previous two sections should have given you some ideas about the
  1976. motivation and use for constructor classes.  It remains to say a few
  1977. words about the way that constructor classes fit into the general Gofer
  1978. framework.  In practice, this means giving a more detailed description
  1979. of the way that the kind system works.
  1980.  
  1981. .ST 4.3.1  Kind errors and the k command line option
  1982. ------------------------------------------------
  1983. As has already been mentioned, Gofer 2.28 uses kind information to
  1984. check that type expressions are well-formed rather than simply checking
  1985. that each type constructor is applied to an appropriate number of
  1986. arguments.  For example, having defined a tree datatype:
  1987.  
  1988.     data Tree a = Leaf a | Tree a :^: Tree a
  1989.  
  1990. the following definition will be rejected as an error:
  1991.  
  1992.     type Example  =  Tree Int Bool
  1993.  
  1994. as follows:
  1995.  
  1996.     ERROR "file" (line 42): Illegal type "Tree Int Bool" in
  1997.                             constructor application
  1998.  
  1999. The problem here is that the Tree constructor has kind * -> * so that
  2000. it expects to take one argument (a type) and deliver a type as the
  2001. result.  On the other hand, in the definition of Example, the Tree
  2002. constructor is treated as having (at least) two arguments; i.e. as
  2003. having a kind of the form (* -> * -> k) for some kind k.  Rather than
  2004. confuse a user who is not familiar with the use of kinds, Gofer
  2005. normally just prints an error message like the one above for examples
  2006. like this.
  2007.  
  2008. If you would like Gofer to give a more detailed description of the
  2009. problem, you can use the :set +k command line option as follows:
  2010.  
  2011.     ? :set +k
  2012.     ? :r
  2013.     Reading script file "file":
  2014.        
  2015.     ERROR "file" (line 42): Kind error in constructor application
  2016.     *** expression     : Tree Int Bool
  2017.     *** constructor    : Tree
  2018.     *** kind           : * -> *
  2019.     *** does not match : * -> a -> b
  2020.  
  2021.     ? 
  2022.  
  2023. When the k command line option has been selected, the :info command
  2024. described in Section 2.3.2 also includes kind information about the
  2025. kinds of type constructors defined in a program.  For example, given
  2026. the definition of Tree above and the datatypes:
  2027.  
  2028.     data STM m s x = STM (s -> m (s, x))
  2029.     data Queue a   = Empty | a :< Queue a | Queue a :> a
  2030.  
  2031. The :info command gives the following kinds (editing the output to
  2032. remove details about constructor functions for each datatype):
  2033.  
  2034.     ? :info Tree STM Queue
  2035.     -- type constructor with kind * -> *
  2036.     data Tree a
  2037.  
  2038.     -- type constructor with kind (* -> *) -> * -> * -> *
  2039.     data STM a b c
  2040.  
  2041.     -- type constructor with kind * -> *
  2042.     data Queue a
  2043.  
  2044.     ?
  2045.  
  2046. In addition to calculating a kind of each type constructor introduced
  2047. in a datatype declaration, Gofer also determines a kind for each
  2048. constructor defined by means of a type synonym.  For example, the
  2049. following definitions:
  2050.  
  2051.     type Subst m v = v -> m v
  2052.     type Compose f g x = f (g x)
  2053.     type Pointer a = Int
  2054.     type Apply f x = f x
  2055.     type Fusion f g x = f x (g x)
  2056.     type Const x y   = x
  2057.  
  2058. are treated as having kinds:
  2059.  
  2060.     ? :info Subst Compose Pointer Apply Fusion Const
  2061.     -- type constructor with kind (* -> *) -> * -> *
  2062.     type Subst a b = b -> a b
  2063.  
  2064.     -- type constructor with kind (* -> *) -> (* -> *) -> * -> *
  2065.     type Compose a b c = a (b c)
  2066.  
  2067.     -- type constructor with kind * -> *
  2068.     type Pointer a = Int
  2069.  
  2070.     -- type constructor with kind (* -> *) -> * -> *
  2071.     type Apply a b = a b
  2072.  
  2073.     -- type constructor with kind (* -> * -> *) -> (* -> *) -> * -> *
  2074.     type Fusion a b c = a c (b c)
  2075.  
  2076.     -- type constructor with kind * -> * -> *
  2077.     type Const a b = a
  2078.  
  2079.     ?
  2080.  
  2081. Note however type synonyms are only used as abbreviations for other
  2082. type expressions.  It is not permitted to use a type synonym
  2083. constructor in a type expression without giving the correct number of
  2084. arguments.
  2085.  
  2086.     ? undefined :: Const Int
  2087.  
  2088.     ERROR: Wrong number of arguments for type synonym "Const"
  2089.     ?
  2090.  
  2091. Assuming that you are familiar with polymorphic functions in Gofer, you
  2092. might be wondering why some of the kinds given for the type synonyms
  2093. above are not also polymorphic in some sense.  After all, the standard
  2094. prelude function const, is defined by
  2095.  
  2096.     const x y = x
  2097.  
  2098. with type a -> b -> a, which looks very similar to the definition of
  2099. the Const type synonym above, except that the kinds of the two
  2100. arguments have both been fixed as *.  In fact, the right hand side of
  2101. a type synonym declaration is always required to have kind *, so this
  2102. would mean that the most general kind that could be assigned to the
  2103. Const constructor would be * -> a -> *.
  2104.  
  2105. Gofer does not currently support the use of polymorphic kinds (let's
  2106. call them polykinds from now on).  First of all, it is not clear what
  2107. practical applications polykinds might offer (I have yet to find an
  2108. example where they are useful).  Furthermore, some of the deeper
  2109. theoretical issues about type inference and related topics have not yet
  2110. been studied and I suspect that polykinds would introduce significant
  2111. complications without any significant benefits.
  2112.  
  2113. The current approach is to replace any unknown part of an inferred kind
  2114. with the kind *.  Any polymorphism in the kind of a constructor
  2115. corresponds much more closely to the idea of a value that is not
  2116. actually used at all than in the language of normal expressions and
  2117. their types so this is unlikely to cause any problems.  And of course,
  2118. in Haskell and previous versions of Gofer, any variable used in a type
  2119. expression was assumed to be a type variable with kind *, so all of the
  2120. kinds above are consistent with this interpretation.
  2121.  
  2122. The rest of this section is likely to get a bit hairy.  Read on at your
  2123. peril, or skip to the start of Section 4.3.2.  Only those with a strong
  2124. interest in the type theory and pragmatics of constructor classes will
  2125. miss anything.
  2126.  
  2127. The same approach is used to determine the kinds of constructor
  2128. variables in type expressions.  In theory, this can sometimes lead to
  2129. problems.  In practice, this only happens in very contrived examples
  2130. and I doubt that any problems will occur for serious applications.  The
  2131. following example illustrates the kind of `problem' that can occur.
  2132. Suppose that we use a script containing the definitions:
  2133.  
  2134.     undefined :: a             -- the `bottom' value
  2135.     undefined  = undefined
  2136.  
  2137.     strange   :: f Tree -> f a
  2138.     strange    = undefined
  2139.     
  2140. The type signature for the `strange' function is indeed very strange;
  2141. the constructor variables f and a have kinds (* -> *) -> * and (* -> *)
  2142. respectively.  What's more, the type is very restrictive.  Without
  2143. including additional primitive constructs in the language, I very much
  2144. doubt that you will be able to find an alternative definition for
  2145. strange which is not semantically equivalent to the definition above.
  2146. And of course, the definition above doesn't really have any practical
  2147. applications anyway.  [In case you don't get my point, I'm trying to
  2148. show that this really is a very contrived example.]  I would be very
  2149. surprised to see a genuine example of a polymorphic operator which
  2150. involves constructor variables of higher kinds in a non-trivial way
  2151. that does not also include overloading constraints as part of the
  2152. type.  For example, it is not at all difficult to think of an
  2153. interesting value of type Monad m => a -> m a, but much harder to think
  2154. of something with type a -> m a (remember this means for all a and for
  2155. all m).
  2156.  
  2157. The definitions of undefined and strange above will be accepted by the
  2158. Gofer system as will the following definition:
  2159.  
  2160.     contrived = strange undefined
  2161.  
  2162. The type of contrived will now be  f a  where f :: (* -> *) -> * and
  2163. a :: (* -> *).  However, if we modify the definition of contrived to
  2164. include a type signature:
  2165.  
  2166.     contrived :: f a
  2167.     contrived  = strange undefined
  2168.  
  2169. then we get a type checking error:
  2170.  
  2171.     ? :l file
  2172.     Reading script file "file":
  2173.     Type checking      
  2174.     ERROR "file" (line 24): Type error in function binding
  2175.     *** term           : contrived
  2176.     *** type           : a b
  2177.     *** does not match : c d
  2178.     *** because        : constructor variable kinds do not match
  2179.  
  2180.     ?
  2181.  
  2182. The problem is that for the declared type signature, the variables f and
  2183. a are treated as having kinds (* -> *) and * respectively.  These do not
  2184. agree with the real kinds for these variables.
  2185.  
  2186. To summarize, what this all means is that it is possible to define
  2187. values whose principal types cannot be expressed within the language of
  2188. Gofer types in the current implementation.  The values defined can
  2189. actually be used within a program, but it would not, for example, be
  2190. possible to allow such values to be exported from a module in a Haskell
  2191. system unless kind annotations were added to the inferred types.
  2192.  
  2193.  
  2194. .ST 4.3.2  The kind of values in a constructor class
  2195. ------------------------------------------------
  2196. The previous section indicated that, if the :set +k command line option
  2197. has been set, the :info command will include information about the
  2198. kinds of type constructor constants in its output.  This will also
  2199. cause the :info command to display information about the kinds of
  2200. classes and constructor classes.  Notice for example in the following
  2201. how the output distinguishes between Eq, a type class, and Functor, a
  2202. constructor class in which each instance has kind (* -> *):
  2203.  
  2204.     ? :info Eq Functor
  2205.     -- type class
  2206.     class Eq a where
  2207.         (==) :: Eq a => a -> a -> Bool
  2208.         (/=) :: Eq a => a -> a -> Bool
  2209.  
  2210.     -- instances:
  2211.     instance Eq ()
  2212.     ...
  2213.  
  2214.     -- constructor class with arity (* -> *)
  2215.     class Functor a where
  2216.         map :: Functor a => (b -> c) -> a b -> a c
  2217.  
  2218.     -- instances:
  2219.     instance Functor []
  2220.     ...
  2221.  
  2222.     ?
  2223.  
  2224.  
  2225. .ST 4.3.3  Implementation of list comprehensions
  2226. --------------------------------------------
  2227. The implementation of overloaded monad comprehensions is cute, but also
  2228. has a couple of potential disadvantages.  These are discussed in this
  2229. section.  As you will see, they really aren't very much to worry
  2230. about.
  2231.  
  2232. First of all, the decision to overload the notation for singleton lists
  2233. so that [ exp ] == result exp can sometimes cause a few surprises:
  2234.  
  2235.     ? map (1+) [1]
  2236.     ERROR: Unresolved overloading
  2237.     *** type        : Monad a => a Int
  2238.     *** translation : map (1 +) [ 1 ]
  2239.  
  2240.     ?
  2241.  
  2242. Note that this will only occur if you are actually using a prelude
  2243. which includes the definition of the Monad class given in Section 4.2
  2244. This can be solved using the command line toggle :set -1 which forces
  2245. any expression of the form [ exp ] to be treated as a singleton list
  2246. rather than being interpreted in an arbitrary monad.  You really
  2247. have to write `result' if you do want an arbitrary monad:
  2248.  
  2249.     ? :set -1
  2250.     ? map (1+) [1]
  2251.     [2]
  2252.     (7 reductions, 18 cells)
  2253.     ? map (1+) (result 1)
  2254.     ERROR: Unresolved overloading
  2255.     *** type        : Monad a => a Int
  2256.     *** translation : map (1 +) (result 1)
  2257.  
  2258.     ?
  2259.  
  2260. This should probably be the default setting, but I have left things as
  2261. they are for the time being, partly so that other people might get the
  2262. chance to find out about this and decide what setting they think would
  2263. be best.  As usual, the default setting can be recovered using the
  2264. :set +1 command.
  2265.  
  2266. A second concern is that the implementation of list comprehensions may
  2267. be less efficient in the presence of monad comprehensions.  Gofer
  2268. usually uses Wadler's `optimal' translation for list comprehensions as
  2269. described in Simon Peyton Jones book.  In fact, this translation will
  2270. always be used if either the prelude being used does not include the
  2271. standard Monad class or the type system is able to guarantee that a
  2272. given monad comprehension is actually a list comprehension.
  2273.  
  2274. If you use a prelude containing the Monad class, you may notice some
  2275. small differences in performance in examples such as:
  2276.  
  2277.     ? [ x * x | x <- [1..10] ]
  2278.     [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
  2279.     (98 reductions, 203 cells)
  2280.  
  2281.     ? f [1..10] where f xs = [ x * x | x <- xs ]
  2282.     [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
  2283.     (139 reductions, 268 cells)
  2284.  
  2285.     ?
  2286.  
  2287. The second expression is a little more expensive since the local
  2288. definition of f is polymorphic with f :: (Num b, Monad a) => a b -> a b
  2289. and hence the implementation of the comprehension in f does not use the
  2290. standard translation for lists.  To be honest, the difference between
  2291. these two functions really isn't anything to worry about in the context
  2292. of an interpreter like Gofer.  And of course, if you really want to
  2293. avoid this problem, an explicit type signature will do the trick (as in
  2294. other cases where overloading is involved):
  2295.  
  2296.     ? f [1..10] where f   :: Num b => [b] -> [b];
  2297.                       f xs = [ x * x | x <- xs ]
  2298.     [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
  2299.     (99 reductions, 205 cells)
  2300.  
  2301.     ? f [1..10] where f   :: [Int] -> [Int]
  2302.                       f xs = [ x * x | x <- xs ]      
  2303.     [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
  2304.     (99 reductions, 203 cells)
  2305.  
  2306.     ?
  2307.  
  2308. As the last example shows, there is only one more reduction in this
  2309. case and that is the reduction step that deals with the application of
  2310. f to the argument list [1..10].
  2311.  
  2312.  
  2313. .co-------------------------------------------------------------------|
  2314. .ST 5. GOFC, THE GOFER COMPILER
  2315.  
  2316. This release of Gofer includes gofc, a `compiler' for Gofer programs
  2317. which translates a large class of Gofer programs into C code which can
  2318. then be compiled and executed as a standalone application.
  2319.  
  2320. Before anybody gets too excited, there are a couple of points which I
  2321. should mention straight away:
  2322.  
  2323.   o  To make use of gofc, you will need a C compiler.  This is why I
  2324.      do not intend to distribute any binary versions of gofc; if you
  2325.      have the C compiler needed to compile the output of gofc then
  2326.      you should also be able to compile gofc from the sources.
  2327.  
  2328.   o  First of all, the Gofer compiler was written by modifying the
  2329.      Gofer interpreter.  Most of the modifications and changes were
  2330.      made in just a few days.  The compiler and interpreter still
  2331.      share a large proportion of code.  As such, and in case it isn't
  2332.      obvious: PLEASE DO NOT expect to gain the same kind of performance
  2333.      out of gofc as you would from one of the serious Haskell
  2334.      projects.  A considerably greater amount of time and effort has
  2335.      gone into those systems.
  2336.  
  2337.   o  The compiler is actually over a year old, but this is the first
  2338.      time it has been released.  Although I have worked with it a bit
  2339.      myself, it hasn't had half the amount of testing that Gofer user's
  2340.      have given the interpreter over the last year and a half.  It may
  2341.      not be as reliable as the interpreter.  If you have problems with
  2342.      a compiled program, try running it with the interpreter too just
  2343.      to check that you haven't found a potential bug in gofc.
  2344.  
  2345. That having been said, I hope that the Gofer compiler will be useful to
  2346. many Gofer users.  One possible advantage is that the executables may
  2347. be smaller than with some other systems.  And of course, the fact that
  2348. gofc runs on some home computers may also be useful.  Finally, gofc
  2349. provides a simplified system for experimenting with the runtime details
  2350. of an implementation.  For example, the source code for the runtime
  2351. system is set up in such a way as to make it possible to experiment
  2352. with alternative garbage collection schemes.
  2353.  
  2354.  
  2355. .ST 5.1  Using gofc
  2356. ---------------
  2357. Compiling a program with gofc is very much like starting up the Gofer
  2358. interpreter.  The compiler starts by reading the prelude and then
  2359. loads the script files specified by the command line.  These scripts
  2360. must contain a definition for the value main :: Dialogue which will be
  2361. the dialogue expression that is evaluated when the compiled program is
  2362. executed.
  2363.  
  2364. For example, if the file apr1.gs contains the simple program:
  2365.  
  2366.     main :: Dialogue
  2367.     main  = appendChan "stdout" "Hello, world\n" exit done
  2368.  
  2369. then this can be compiled as:
  2370.  
  2371.     machine% gofc apr1.gs
  2372.     Gofer->C Version 1.01 (2.28)  Copyright (c) Mark P Jones 1992-1993
  2373.     
  2374.     Reading script file "/usr/local/lib/Gofer/standard.prelude":
  2375.     Reading script file "apr1.gs":
  2376.                    
  2377.     Writing C output file "apr1.c":
  2378.     [Leaving Gofer->C]
  2379.     machine% 
  2380.  
  2381. The output is written to the file apr1.c -- i.e. the name obtained by
  2382. removing the .gs suffix and replacing it with a .c suffix.  Other
  2383. filename suffixes that are treated in a similar way are:
  2384.  
  2385.     .prj    .gp                   for Gofer project files
  2386.  
  2387.     .prelude                      for Gofer prelude files
  2388.  
  2389.     .gof    .gs                   for Gofer scripts
  2390.  
  2391.     .has    .hs                   for Haskell scripts
  2392.  
  2393.     .lhs    .lit                  for literate scripts
  2394.     .lgs    .verb
  2395.  
  2396. If no recognized suffix is found then the name of the output file is
  2397. obtained simply by appending the .c suffix to the input name.
  2398.  
  2399. For the benefit of those using Unix systems, let me point out that this
  2400. could cause you problems if you are not careful; if you take an input
  2401. file called `prog' and compile it to `prog.c' using gofc, make sure
  2402. that you do not compile the C program in such a way that the output is
  2403. also called `prog' since this will overwrite your original source code!
  2404. For this reason, I would always suggest using file extensions such as
  2405. the .gs example above if you are using gofc.
  2406.  
  2407. If you run gofc with multiple script files, then the name of the output
  2408. file is based on the last script file to be loaded.  For example, the
  2409. command `gofc prog1.gs prog2.gs' produces an output file `prog2.c'.
  2410.  
  2411. Gofc also works with project files, using the name of the project file
  2412. to determine the name of the output file.  For example, the miniProlog
  2413. interpreter can be compiled using:
  2414.  
  2415.     machine% gofc + miniProlog
  2416.     Gofer->C Version 1.01 (2.28)  Copyright (c) Mark P Jones 1992-1993
  2417.  
  2418.     Reading script file "/usr/local/lib/Gofer/standard.prelude":
  2419.     Reading script file "Parse":
  2420.     Reading script file "Interact":
  2421.     Reading script file "PrologData":
  2422.     Reading script file "Subst":
  2423.     Reading script file "StackEngine":
  2424.     Reading script file "Main":
  2425.                    
  2426.     Writing C output file "miniProlog.c":
  2427.     [Leaving Gofer->C]
  2428.     machine% 
  2429.  
  2430. This is another case where it might well have been sensible to have
  2431. used a .prj or .gp for the project file miniProlog since compiling the
  2432. C code in miniProlog.c to a file named `miniProlog' will overwrite the
  2433. project file!  Choose filenames with care!
  2434.  
  2435. You can also specify Gofer command line options as part of the command
  2436. line used to run gofc.  Think of it like this; use exactly the same
  2437. command line to start Gofc as you would have done to start Gofer (ok,
  2438. replacing the command `gofer' with `gofc') so that you could start your
  2439. program immediately by evaluating the main expression.  To summarize
  2440. what happens next:
  2441.  
  2442.   o  Gofc will load the prelude file.  Do not worry if the prelude
  2443.      (or indeed, later files) contain lots of definitions that your
  2444.      program will not actually use; only definitions which are actually
  2445.      required to evaluate the main expression will be included in the
  2446.      output file.
  2447.  
  2448.   o  Gofc will load the script files specified.  If an error is found
  2449.      then an error message will be printed and the compilation will be
  2450.      aborted.  You would probably be sensible to run your program
  2451.      through the interpreter first to tidy up any errors and avoid this
  2452.      problem.
  2453.  
  2454.   o  Gofc will look for a definition of `main' and check that it has
  2455.      type Dialogue.  You will get an error if an appropriate main
  2456.      value cannot be found.
  2457.  
  2458.   o  Gofc determines the appropriate name for the output file.
  2459.  
  2460.   o  Gofc checks to make sure that you haven't used a primitive
  2461.      function that is not supported by the runtime system (see
  2462.      Section 5.2 for more details).
  2463.  
  2464.   o  Gofc outputs a C version of the program in the output file.
  2465.  
  2466. Once you have compiled the Gofer program to C, you need to compile
  2467. the C code to build the executable application program.  This will
  2468. vary from one system to another and is documented elsewhere.
  2469.  
  2470.  
  2471. .ST 5.2  Primitive operations
  2472. -------------------------
  2473. The Gofer compiler accepts the same source language as the
  2474. interpreter.  However, there is a small collection of Gofer primitives
  2475. which are only implemented in the interpreter.  The most likely
  2476. omission that you will notice is the primPrint function which is used
  2477. to define the show' function in the standard prelude.  Omitting this
  2478. function is not an indication of laziness on my part; it is impossible
  2479. to implement primPrint in the current runtime system because there is
  2480. insufficient type information available at program runtime.
  2481.  
  2482. .cc 5
  2483. For example, if you try to compile the program:
  2484.  
  2485.     main :: Dialogue
  2486.     main  = appendChan "stdout" (show' 42) exit done
  2487.  
  2488. the compiler will respond with the error message:
  2489.  
  2490.     ERROR: Primitive function primPrint is not
  2491.            supported by the gofc runtime system
  2492.            (used in the definition of show')
  2493.     Aborting compilation
  2494.  
  2495. The solution is to use type classes.  This is one of the reasons for
  2496. including them in the language in the first place.  This example can
  2497. be compiled by changing the original program to:
  2498.  
  2499.     main :: Dialogue
  2500.     main  = appendChan "stdout" (show 42) exit done
  2501.  
  2502. (Remember that show is the overloaded function for converting values of
  2503. any type a that is an instance of the Text class to a string value.)
  2504.  
  2505.  
  2506. .ST 5.3  Debugging output
  2507. ---------------------
  2508. Another potentially useful feature of gofc is it's ability to dump a
  2509. listing of all the supercombinator definitions that are created by
  2510. loading a particular combination of script files.  For the time being,
  2511. this is only useful for the purpose of debugging, but with only small
  2512. modifications, it might be possible to use this as input to an
  2513. alternative backend/code generator system (the format of the output
  2514. combinators already uses explicit layout characters to make the task of
  2515. parsing easier in an application like this).
  2516.  
  2517. To illustrate how this option might be used, suppose that we were working
  2518. on a program containing the definition:
  2519.  
  2520.     hidden xs = map (\[x] -> x) xs
  2521.  
  2522. and that somewhere during the execution of our program, this function is
  2523. applied to a list value [[1],[1,2]]:
  2524.  
  2525.     ? hidden [[1],[1,2]]
  2526.     [1, 
  2527.     Program error: {v132 [1, 2]}
  2528.     (13 reductions, 75 cells)
  2529.  
  2530.     ?
  2531.  
  2532. The variable v132 which appears here is the name used internally to
  2533. represent the lambda expression in the definition of hidden.  For this
  2534. particular example, it is fairly easy to work this out, but in general,
  2535. it may not be so straightforward.  Running the program through gofc and
  2536. using the +D toggle as follows produces an output file containing Gofer
  2537. SuperCombinators, hence the .gsc suffix:
  2538.  
  2539.     machine% gofc +D file
  2540.     Gofer->C Version 1.01 (2.28)  Copyright (c) Mark P Jones 1992-1993
  2541.  
  2542.     [Writing supercombinators to "file.gsc"]
  2543.     Reading script file "/usr/local/lib/Gofer/standard.prelude":
  2544.     Reading script file "file":
  2545.     [Leaving Gofer->C]
  2546.     machine% 
  2547.  
  2548. Note that there is no need in this situation for the files loaded to
  2549. contain a definition for main :: Dialogue, although the compiler must
  2550. be loaded using exactly the same prelude and order of files as in the
  2551. original Gofer session to ensure that the same names are used.  Scanning
  2552. the output file, we find that the only mention of v132 is in the
  2553. definitions:
  2554.  
  2555.     v132 o1 = case o1 of {
  2556.                 (:) o3 o2 -> case o2 of {
  2557.                                [] -> o3;
  2558.                              }
  2559.               }
  2560.  
  2561.     hidden o1 = map v132 o1;
  2562.  
  2563. This shows fairly clearly where the function v132 comes from.  Of
  2564. course, this is far from perfect, but it might help someone to track
  2565. down a bug that little bit faster one day.  It's better than nothing.
  2566.  
  2567. Of course, the debugging output might also be of interest to anyone
  2568. that wants to find out more about the implementation of Gofer and
  2569. examine the supercombinator definitions generated when list
  2570. comprehensions, overloading, local function definitions etc.  have all
  2571. been eliminated.  For example, the standard prelude definitions of map
  2572. and filter become:
  2573.  
  2574.     map o2 o1 = case o1 of {
  2575.                   [] -> [];
  2576.                   (:) o4 o3 -> o2 o4 : map o2 o3;
  2577.                 }
  2578.  
  2579.     filter o2 o1 = case o1 of {
  2580.                      [] -> [];
  2581.                      (:) o4 o3 -> let { o5 = filter o2 o3;
  2582.                                   } in  | o2 o4 -> o4 : o5;
  2583.                                         | otherwise -> o5;
  2584.                    }
  2585.  
  2586. This is one of the tools I'll be using if anyone ever reports another
  2587. bug in the code generator...
  2588.  
  2589.  
  2590. .co-------------------------------------------------------------------|
  2591. .ST 6. SOME HISTORY
  2592.  
  2593. Ever since the first version of Gofer was released I've had requests
  2594. from Gofer users around the world asking how Gofer got its name and how
  2595. it came into being.  This section is an attempt to try and answer those
  2596. questions.
  2597.  
  2598. .ST 6.1  Why Gofer?
  2599. ---------------
  2600. Everything has to have a name.  You may type in an `anonymous function'
  2601. as a lambda expression but Gofer will still go ahead and give it a
  2602. name.  To tell the truth, I always intended the name `Gofer' to be
  2603. applied to my particular implementation of a functional programming
  2604. environment, not to the language on which it is based.  I wanted that
  2605. to be an anonymous language.  But common usage has given it the same
  2606. name, Gofer.
  2607.  
  2608. If you take a look in a dictionary (as some puzzled Gofer users have)
  2609. you'll find that `gofer' means:
  2610.  
  2611.      ``an employee whose duties include running errands''
  2612.  
  2613. (although you'd better choose a dictionary printed since the 70s for
  2614. this).  I'd not thought about this when I chose the name (and I would
  2615. have used a lower case g instead of an upper case G if I had).  In
  2616. fact, Gofer was originally conceived as a system for machine assisted
  2617. equational reasoning.  One of the properties of functional languages
  2618. that I find particularly attractive is that they are:
  2619.  
  2620.     GOod For Equational Reasoning.
  2621.     ^^   ^   ^          ^
  2622. So now you know.  The fact that you can also tell someone who is having
  2623. a problem with their C program to ``Gofer it!'' (unsympathetic, I know)
  2624. is nothing more than a coincidence.  Fairly recently, somebody wrote to
  2625. ask if Gofer stood for ``GOod Functional programming EnviRonment''. I
  2626. was flattered; I wish I'd thought of that one.
  2627.  
  2628. Some people have asked me why I didn't choose a title including the
  2629. name `Haskell', a language on which Gofer is very strongly based.
  2630. There are two reasons for this.  To start with, the original version of
  2631. Gofer was based on a different syntax, Orwell + type classes.  The
  2632. Haskell influence only crept in when I started on version 2.xx.
  2633. Secondly, it's only right to point out that there is quite a large gap
  2634. between a system like Gofer and the full blown Haskell systems that
  2635. have been developed.  Using a name which doesn't involve `Haskell'
  2636. directly seemed the right thing to do.  Some people tell me that it was
  2637. a mistake.  One of the objectives of Haskell was to create a standard
  2638. language for non-strict functional programming.  Gofer isn't intended
  2639. as an alternative to Haskell and I hope it will continue to grow closer
  2640. as time passes.
  2641.  
  2642. While I'm on the subject of names, I should also talk about an
  2643. additional source of confusion that may sometimes crop up.  While Gofer
  2644. is a functional programming system, there is also a campus wide
  2645. information system called `Gopher' (sharing it's name with the North
  2646. American rodents).  I would guess that the latter has many more users
  2647. than the former.  So please be careful to spell Gofer with an `f' not
  2648. a `ph' to try and minimize the confusion.
  2649.  
  2650. It has occurred to me that I should try and think of another name for
  2651. Gofer to avoid the confusion with Gopher.  I hope that won't be
  2652. necessary, but if you have a really good suggestion, let me know!  One
  2653. possibility might be to call it `Gordon'.  The younger generation of
  2654. brits might know what the connection is.  Others may need to ask their
  2655. children...
  2656.  
  2657. .ST 6.2  The history of Gofer
  2658. -------------------------
  2659. Here is a summary of the way that I first learnt about functional
  2660. programming, and how it started me on the path to writing Gofer.
  2661. This, slightly sentimental review is mostly for my own entertainment.
  2662. If you're the sort of person that likes to read the acknowledgments
  2663. and bibliographic notes in a thesis: this is for you.  If not, you
  2664. can always stop reading :-)
  2665.  
  2666. My first exposure to lazy functional programming languages was using a
  2667. language called `Orwell' developed and used at the Programming Research
  2668. Group in Oxford.  I've been interested in using and implementing lazy
  2669. functional programming languages ever since.
  2670.  
  2671. One of the properties of programming in Orwell that appealed to me was
  2672. the ability to use equational reasoning -- a very simple style of
  2673. mathematical reasoning -- to establish properties of programs and prove
  2674. that they would behave in particular ways.  Even more interesting,
  2675. equational reasoning can be used to calculate efficient implementations
  2676. of programs from a formal specification of what was intended.
  2677.  
  2678. Probably the first non-trivial functional program that I wrote was a
  2679. simple Prolog interpreter.  (This was originally written in Orwell and
  2680. later transcribed to be compiled using the Chalmers Haskell B compiler,
  2681. hbc.  The remnants of this program live on in the mini Prolog
  2682. interpreter that is included with the Gofer distribution and, I
  2683. believe, with at least a couple of the big Haskell systems.) Using a
  2684. sequence of something like a dozen or so transformations (most of which
  2685. were fairly mundane), I discovered that I could turn a relatively
  2686. abstract specification of a Prolog inference engine into a program that
  2687. could be interpreted as the definition of a low level stack-based
  2688. machine for executing Prolog queries.  Indeed, I used the result as the
  2689. core of a C implementation of mini Prolog.
  2690.  
  2691. The transformations themselves were simple enough but managing the
  2692. complexity of the calculations was tough.  It was not uncommon to find
  2693. that some of the intermediate steps in a calculation would span more
  2694. than 200 characters.  Even with a relatively small number of
  2695. transformation steps, carrying out proofs like this was both tedious
  2696. and prone to mistakes.  A natural application for a computer!
  2697.  
  2698. Here's an outline of what happened next:
  2699.  
  2700.    eqr   1989.  Eqr was a crude tool for machine assisted equational
  2701.          reasoning.  It worked well enough for the job I had intended
  2702.          to use it for, but it also had a number of problems.  I
  2703.          particularly missed the ability to use and record type
  2704.          information as part of an automated derivation.
  2705.  
  2706.    1.xx  1990.  Gofer 1.xx was intended to be the next step forward
  2707.          providing machine support for *typed* equational reasoning.
  2708.          It was based on Orwell syntax and was later extended to
  2709.          support Haskell style type classes.  It had a lexer, parser,
  2710.          type checker and simple top-level interactive loop.  It
  2711.          couldn't run programs or construct derivations.
  2712.  
  2713.    2.xx  January 1991.  A complete rewrite.  I remember those early
  2714.          days, several months passed before I ever got compile some of
  2715.          the earliest code.  The emphasis switched to being able to run
  2716.          programs rather than derive them when I came up with a new
  2717.          implementation technique for type classes in February 1991.
  2718.          If I wanted to see it implemented, I was going to have to do
  2719.          it myself.  Around about May, I realized I had something that
  2720.          might be useful to other people.
  2721.  
  2722.    2.20  The first public release, announced in August 1991 and
  2723.          distributed shortly after that in September.
  2724.  
  2725.    2.21  November 1991, providing a more comprehensive user
  2726.      interface, access to command line options and fixing a
  2727.      small number of embarrassing bugs in the original release.
  2728.  
  2729.    2.23  August 1992, having been somewhat preoccupied with academic
  2730.      studies for some time, the main purpose of this release
  2731.      was to correct a number of minor bugs which had again been
  2732.      discovered, either by myself or by one or more of the many
  2733.      Gofer users out there.
  2734.  
  2735.    2.28  January 1993.  The most substantial update to Gofer since
  2736.      the original release.  I had been doing a lot of work and
  2737.      experimentation with Gofer during the time between the
  2738.      release of versions 2.21 and 2.23, but I didn't have the
  2739.      time to get these extensions suitable for public distribution.
  2740.      By the time I came to release version 2.23, I also had
  2741.      several other distinct versions of Gofer (each derived
  2742.      from the source for version 2.21) including a compiler
  2743.      and a prototype implementation of constructor classes
  2744.      which was called `ccgofer'.   Work on version 2.28 started
  2745.      with efforts to merge these developments back into a single
  2746.      system (I was tired of trying to maintain several different
  2747.      versions, even though I was the only one using them).
  2748.      The rough outline of changes was as follows (with the
  2749.      corresponding version numbers for those who wonder why
  2750.      2.28 follows 2.23):
  2751.  
  2752.             2.24   enhancements and bug fixes
  2753.             2.25   merging in support for the Gofer compiler
  2754.             2.26   a reimplementation of constructor classes
  2755.             2.27   reworked code generator and other minor fixes
  2756.             2.28   preparation for public release
  2757. .co-------------------------------------------------------------------|
  2758.