Doc: Initiate transition to next generation documentation
[shapes.git] / doc / parts / tutorial / chap-prog.sxml
blobde65d0658b6550c12e7fe97e31bd4dad64b8949e
1 <!-- This file is part of Shapes.                                           -->
2 <!--                                                                        -->
3 <!-- Shapes is free software: you can redistribute it and/or modify         -->
4 <!-- it under the terms of the GNU General Public License as published by   -->
5 <!-- the Free Software Foundation, either version 3 of the License, or      -->
6 <!-- any later version.                                                     -->
7 <!--                                                                        -->
8 <!-- Shapes is distributed in the hope that it will be useful,              -->
9 <!-- but WITHOUT ANY WARRANTY; without even the implied warranty of         -->
10 <!-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the          -->
11 <!-- GNU General Public License for more details.                           -->
12 <!--                                                                        -->
13 <!-- You should have received a copy of the GNU General Public License      -->
14 <!-- along with Shapes.  If not, see <http://www.gnu.org/licenses/>.        -->
15 <!--                                                                        -->
16 <!-- Copyright 2008, 2015 Henrik Tidefelt                                   -->
18 <section id="chap-prog">
19 <title>Programming</title>
20 <top>
21 <p>Under this overly generic title, we'll discuss basic programming concepts, such as states, functions, and structures.  As usual, we'll often do this by giving relevant pointers to the reference documentation.</p>
22 </top>
24 <section id="prog/bracket">
25 <title>The code bracket</title>
26 <body>
28         <p>
29                 We have already seen how variable bindings can be introduced, like this:
30 <pre>
31 a: 8 + 7
32 </pre>
33     but we have not yet discussed where such code may appear.  The proper place to introduce a variable binding is a <em>code bracket</em>.  A complete <str-Shapes /> program is implicitly enclosed in a code bracket, and the user may introduce new code brackets by using the delimiters <inline>{</inline> and <inline>}</inline>.</p>
35 <p>
36   Here, the sum of 7 and 8 is squared by using a variable binding for the sum, and then multiplying that variable by itself:
37 <pre>
39   a: 8 + 7
40   a * a
42 </pre>
43         </p>
45         <p>Code brackets serve many purposes.  To learn more, see <syntax name="code-bracket" />.</p>
46 </body>
47 </section><!-- End of prog/bracket -->
49 <section id="prog/functions">
50 <title>Functions, and the lexical and dynamic environments</title>
51 <body>
52         <p>In this section, the <em>pure functions</em> will be introduced.  These are my favorite function-like abstraction, and hence what you will find in most code examples.  Other function-like abstractions will be introduced later, after <em>state</em> have been properly introduced.</p>
54         <p>A function has no side effects.  Given arguments and a <em>dynamic</em> environment, a function returns a value.  Given the same arguments and the same dynamic environment, the function will always return the same result.  This implies that a function must not be allowed to access anything which can change from time to time.  In <str-Shapes /> these things which can change are the <em>states</em>, so the rule is simply that a pure function is not allowed to access any states.  Note that this does not mean a function cannot use states internally to compute its result.</p>
56         <p>
57                 The following example shows how a function is constructed:
58 <pre>
59 textGreater: \ x y .> [if x > y `true´ `false´]
60 </pre>
61     The <em>formal parameters</em> appear between <inline>\</inline> and <inline>.&gt;</inline>, and the expression that follows is the <em>body</em> of the function.  The result of calling the function is obtained by evaluating the body, with the formal parameters added to the <em>lexical scope</em>  For instance,
62 <pre>
63 <![CDATA[•stdout << [textGreater 4 5]]]>
64 </pre>
65     would result in <em>false</em> being written to <filename>stdout</filename>.
66         </p>
68         <p>The above example code shows what a typical function call looks like, with the callee and arguments enclosed in square brackets.  When there is only one argument, one may reorder things a little:
69 <pre>
70 <![CDATA[•stdout << sin [] 30°]]>
71 </pre>
73 <pre>
74 <![CDATA[•stdout << 30° >> sin]]>
75 </pre>
76 Please read the short discussion about <a part="syntax" id="syntax/fun-apply/unary">unary calls</a> at this time.</p>
78         <p>
79                 Let us also show how <a part="syntax" id="syntax/fun-apply/cute-basic">evaluated cuts</a> can be used to bind just some of the arguments of a function:
80 <pre>
81 <![CDATA[textGreaterThanEight: [textGreater y:8 ...]]]>
82 </pre>
83 In combination with evaluated cuts of <value name="debuglog_after" />, <operator name="&gt;&gt;" /> provides a rather clean way to write stuff to the log file at an arbitrary location in the program.  Here is an exmaple:
84 <pre>
85 <![CDATA[fun: \ a →
86   {
87     b: 10 * a
88     a + b
89       >> [debuglog_after ( newString << `The value of a is ´ << a << "{n} ) ...]
90       >> [debuglog_after ( newString << `The value of b is ´ << b << "{n} ) ...]
91   }]]>
92 </pre>
93 Recall that global states such as <state name="stderr" /> is not in scope inside the function body, but by making <filename>stderr</filename> the debug log file (see <a part="man" id="debuglog">man page</a>), this is a way to get around the function's scoping barrier.
94         </p>
96   <p>There is much more to say about evaluated cuts, but we refer to the language reference (including the section linked above, but please note that there are other related sections as well), and just include an example here.</p>
98 <example-with-output title="Evaluated cuts" internal-id="example:cute">
99 <source file="features/curry.blank">
100 <![CDATA[<!--#include depth="0" virtual="$(BUILDDIR)$(EXAMPLES)features/curry.blank" -->]]>
101 </source>
102 <stdout>
103 <![CDATA[<!--#include depth="0" virtual="$(BUILDDIR)$(EXAMPLES)features/curry.stdout" -->]]>
104 </stdout>
105 <caption>
106         <p>Evaluated cuts may take some time to grok.  Use this example as an exercise!</p>
107 </caption>
108 </example-with-output>
110         <p>Function taking an arbitrary number of arguments can be defined by the use of a <syntax name="sink" />.  This is an advanced topic, also discussed in <a part="syntax" id="syntax/compound/structures" />.</p>
112         <p>The lexical scope is the set of bindings which can be “seen” from a particular point in the code.  This is a very common concept, explained in more detail in <a part="syntax" id="syntax/binding/lexical" /> (where the reader will also find the example included below), and the reader is referred to <a method="google" query='"lexical binding"'/> for further in-depth discussions.  One thing to note about the lexical scope in <str-Shapes />, though, is that when a new binding is introduced, the scope where the binding is introduced is in scope where the right hand side expression is evaluated.  That is, defining (mutually) recursive functions is trivial.</p>
114 <example-with-output title="Lexical binding" internal-id="example:lexical-binding">
115 <source file="features/scopes.blank">
116 <![CDATA[<!--#include depth="0" virtual="$(BUILDDIR)$(EXAMPLES)features/scopes.blank" -->]]>
117 </source>
118 <stdout>
119 <![CDATA[<!--#include depth="0" virtual="$(BUILDDIR)$(EXAMPLES)features/scopes.stdout" -->]]>
120 </stdout>
121 <caption>
122         <p>Lexical scoping rules in <str-Shapes /> make it easy to define (mutually) recursive functions.  To access bindings shadowed in the current scope, one can <em>reach out</em> by using the <inline>../</inline> construct.</p>
123 </caption>
124 </example-with-output>
126 <p>Dynamic bindings, recognized by being prefixed with the at sign (@) differ from lexical bindings in that one cannot determine where they were bound by a lexical analysis of the code.  Instead, one must (conceptually) unwind the chain of function calls to find the closest point where the dynamic variable was bound.  We have already seen dynamic variables in use in <a id="basics/colors" />, although the examples seen there were very simple and did not really display the power of dynamic binding.  The main documentation is in  <a part="syntax" id="syntax/binding/dynamic" /> (the example below also appears there), but interested readers should also try <a method="google" query='"dynamic binding" lexical' /> for further in-depth discussions.  The thing to note about dynamic bindings in <str-Shapes /> is that a dynamic variable can be bound to an expression that is to be evaluated each time the dynamic variable is accessed.  This feature i called an <em>dynamic expression</em> (note that these can only be bound to dynamic variables).</p>
128 <p>Since dynamic bindings and the way it is accomplished in <str-Shapes /> is a very important topic for this tutorial, study the following examples carefully!  The first example just motivates the notation used for one of the operators used to combine dynamic bindings, do not expect to understand this example completely until after reading the second example.</p>
130 <example-with-output title="Notation of the asymmetric binding union operator" internal-id="example:asymmetric-notation">
131 <image pdf="features/asymmetric-notation_3.pdf" jpg="features/asymmetric-notation_y_small.jpg" />
132 <source file="features/asymmetric-notation.shape">
133 <![CDATA[<!--#include depth="0" virtual="$(BUILDDIR)$(EXAMPLES)features/asymmetric-notation.shape" -->]]>
134 </source>
135 <caption>
136         <p>The story behind the notation of the operator <operator name="&amp;|" />, and a typical application of it.</p>
137 </caption>
138 </example-with-output>
140 <example-with-output title="Dynamic binding" internal-id="example:dynamic-binding">
141 <source file="features/dynamic.blank">
142 <![CDATA[<!--#include depth="0" virtual="$(BUILDDIR)$(EXAMPLES)features/dynamic.blank" -->]]>
143 </source>
144 <stdout>
145 <![CDATA[<!--#include depth="0" virtual="$(BUILDDIR)$(EXAMPLES)features/dynamic.stdout" -->]]>
146 </stdout>
147 <caption>
148         <p>Dynamic scoping in <str-Shapes /> allows for both dynamically bound variables and dynamically evaluated expressions.  The keyword <inline>dynamic</inline> is used both for introducing new dynamic bindings and to indicate that an expression is to be evaluated dynamically.</p>
149 </caption>
150 </example-with-output>
152 </body>
153 </section><!-- End of prog/functions -->
155 <section id="prog/states">
156 <title>States</title>
157 <body>
158         <p>By now, we know that a pure function may not access states, and we have seen the globally defined states <state name="page" /> and <state name="stdout" /> in use in the examples.  Here, the reader will learn how to set up new states, and what the basic operations on states are.  How states are used with non-pure functions is postponed until <a id="prog/non-pure" />.</p>
160         <p>
161                 A state may be introduced in a code bracket just like a variable binding:
162 <pre>
163 •myState: newGroup
164 </pre>
165     The right hand side is a value that is able to spawn new states, see <a part="bindings" id="bindings/hot" /> for the globally bound values with such capability.
166         </p>
168         <p>The states themselves are of <em>state type</em>.  For instance, <state name="page" /> is of type <named-state-type name="Group" />.  The operations on a state which we are about to describe briefly are further described in the documentation for state types.</p>
170         <p>
171                 There are three basic operations, <em>tack on</em>, <em>peek</em>, and <em>freeze</em>.  The first of these looks like a <str-C-plus-plus /> insertion operation, and may repeated:
172 <pre>
173 •myState &lt;&lt; (TeX `Hello!´)
174          &lt;&lt; [stroke (1cm,1cm)--(2cm,0cm)]
175 </pre>
176     The state is free to modify itself as it pleases when values are tacked on to it.
177         </p>
179         <p>
180                 The next operation, <em>peek</em>, may also modify the state, but shall also return a value somehow representing the current state of the state.  The syntax is simply to enclose the state in parentheses:
181 <pre>
182 picture: (•myState)
183 </pre>
184     Not all state types allows the state to be peeked, usually for efficiency reasons.
185         </p>
187         <p>
188                 The last operation, <em>freeze</em>, returns a value representing the state, and renders the state unusable in the future.  This allows for efficient implementation.  The state is frozen by writing a semicolon after the state, and this operation is only allowed as the right hand side of a variable binding, or as the last statement in a code bracket.  For instance,
189 <pre>
190 finalState: •myState;
191 </pre>
192     Not all state types allows the state to be frozen.
193         </p>
195         <p>
196                 States can also be used without naming the state.  For instance:
197 <pre>
198 picture: ( newGroup &lt;&lt; (TeX `Hello!´) &lt;&lt; [stroke (1cm,1cm)--(2cm,0cm)] )
199 </pre>
200    gives the same result as
201 <pre>
202 picture: ( (TeX `Hello!´) &amp; [stroke (1cm,1cm)--(2cm,0cm)] )
203 </pre>
204         </p>
206         <p>We end this section with an example.</p>
208 <example-with-output title="States" internal-id="example:states">
209 <source file="features/states.blank">
210 <![CDATA[<!--#include depth="0" virtual="$(BUILDDIR)$(EXAMPLES)features/states.blank" -->]]>
211 </source>
212 <stdout>
213 <![CDATA[<!--#include depth="0" virtual="$(BUILDDIR)$(EXAMPLES)features/states.stdout" -->]]>
214 </stdout>
215 <caption>
216         <p>States allow imperative style programming to some extent in <str-Shapes />.  This example also illustrates non-pure functions, which have not yet been discussed.</p>
217 </caption>
218 </example-with-output>
220 </body>
221 </section><!-- End of prog/states -->
223 <section id="prog/non-pure">
224 <title>Non-pure functions</title>
225 <body>
227         <p>A <em>non-pure function</em> is like a pure function, except that it also takes state arguments by reference.  This means that the result of a non-pure function call cannot be cached for reuse, and that the side effects the function may have are limited to the states explicitly passed in the call.</p>
229         <p>Non-pure functions are defined just like pure functions, and called the same way.  The only difference is that states appear among the formal parameters, and that states needs to be passed for these formal parameters.  The following example shows how a non-pure function is used to add a stroke to <state name="page" />:
230 <pre>
231 mark: \ •dst .> { •dst &lt;&lt; [stroke (0cm,0cm)--(1cm,1cm)] }
232 [mark •page]
233 </pre>
234         </p>
236         <note>
237                 <p>A non-pure expression such as <inline>[mark •page]</inline> may be used as a <em>statement</em>, which is completely unlike a pure expression such as <inline>[stroke (0cm,0cm)--(1cm,1cm)]</inline>.  Statements may appear anywhere in a code bracket, while expressions only make sense at the end of a code bracket.</p>
238         </note>
240         <note>
241                 <p>When a function is called, the formal parameters are bound in a scope where the body of the function is then evaluated.  One can think of this scope as a barrier through which states cannot be reached.  In early versions of <str-Shapes />, there were also <em>procedures</em>, which did not have such a barrier.  Their use had to be controlled in certain ways during runtime, were always consiered an ugly feature of the language until the day they were removed.  They could be removed without the pain that usually comes with backwards incompatible changes, simply because they had never been used in applications.</p>
242         </note>
244         <p>See the example under <a id="prog/states" /> for more examples.</p>
246 </body>
247 </section><!-- End of prog/non-pure -->
250 <section id="prog/structure">
251 <title>Structures</title>
252 <body>
254         <p><em>Structures</em> are the simple means for data abstraction currently supported by <str-Shapes />.</p>
256         <p>
257                 A common application of structures that a user may need to know about is arrowheads.  An arrowhead function shall, given a path, return a length that the path shall be shortened by, and a picture that is the actual arrowhead.  This would be a valid arrowhead function:
258 <pre>
259 \ pth .>
260   (&gt;
261     cut: 2mm
262     picture: [fill [circle 1mm]] >> [shift pth.begin.p]
263   &lt;)
264 </pre>
265    Note that the names of the field in the structure is part of the structure's type, and hence of the function's signature.
266         </p>
268         <p>Structures have many uses.  Please refer to <a part="syntax" id="syntax/compound/structures" /> for an example and more details.</p>
270 </body>
271 </section><!-- End of prog/structures -->
274 </section><!-- End of chap-prog -->