Improves tut1.txt with more hyperlinks and minor fixes.

This commit is contained in:
Grzegorz Adam Hankiewicz 2014-08-05 14:49:56 +02:00
commit 688db0f70a

View file

@ -18,9 +18,8 @@ Introduction
This document is a tutorial for the programming language *Nimrod*. This document is a tutorial for the programming language *Nimrod*.
This tutorial assumes that you are familiar with basic programming concepts This tutorial assumes that you are familiar with basic programming concepts
like variables, types or statements but is kept very basic. The manual like variables, types or statements but is kept very basic. The `manual
contains many more examples of the advanced language features. <manual.html>`_ contains many more examples of the advanced language features.
@ -40,9 +39,9 @@ Save this code to the file "greetings.nim". Now compile and run it::
nimrod compile --run greetings.nim nimrod compile --run greetings.nim
With the ``--run`` switch Nimrod executes the file automatically With the ``--run`` `switch <nimrodc.html#command-line-switches>`_ Nimrod
after compilation. You can give your program command line arguments by executes the file automatically after compilation. You can give your program
appending them after the filename:: command line arguments by appending them after the filename::
nimrod compile --run greetings.nim arg1 arg2 nimrod compile --run greetings.nim arg1 arg2
@ -56,7 +55,8 @@ To compile a release version use::
By default the Nimrod compiler generates a large amount of runtime checks By default the Nimrod compiler generates a large amount of runtime checks
aiming for your debugging pleasure. With ``-d:release`` these checks are aiming for your debugging pleasure. With ``-d:release`` these checks are
turned off and optimizations are turned on. `turned off and optimizations are turned on
<nimrodc.html#compile-time-symbols>`_.
Though it should be pretty obvious what the program does, I will explain the Though it should be pretty obvious what the program does, I will explain the
syntax: statements which are not indented are executed when the program syntax: statements which are not indented are executed when the program
@ -65,9 +65,10 @@ done with spaces only, tabulators are not allowed.
String literals are enclosed in double quotes. The ``var`` statement declares String literals are enclosed in double quotes. The ``var`` statement declares
a new variable named ``name`` of type ``string`` with the value that is a new variable named ``name`` of type ``string`` with the value that is
returned by the ``readLine`` procedure. Since the compiler knows that returned by the `readLine <system.html#readLine,TFile>`_ procedure. Since the
``readLine`` returns a string, you can leave out the type in the declaration compiler knows that `readLine <system.html#readLine,TFile>`_ returns a string,
(this is called `local type inference`:idx:). So this will work too: you can leave out the type in the declaration (this is called `local type
inference`:idx:). So this will work too:
.. code-block:: Nimrod .. code-block:: Nimrod
var name = readLine(stdin) var name = readLine(stdin)
@ -75,10 +76,10 @@ returned by the ``readLine`` procedure. Since the compiler knows that
Note that this is basically the only form of type inference that exists in Note that this is basically the only form of type inference that exists in
Nimrod: it is a good compromise between brevity and readability. Nimrod: it is a good compromise between brevity and readability.
The "hello world" program contains several identifiers that are already The "hello world" program contains several identifiers that are already known
known to the compiler: ``echo``, ``readLine``, etc. These built-ins are to the compiler: ``echo``, `readLine <system.html#readLine,TFile>`_, etc.
declared in the system_ module which is implicitly imported by any other These built-ins are declared in the system_ module which is implicitly
module. imported by any other module.
Lexical elements Lexical elements
@ -154,11 +155,11 @@ the syntax, watch their indentation:
when false: when false:
brokenCode() brokenCode()
Another option is to use the `discard`_ statement together with Another option is to use the `discard statement`_ together with *long string
*long string literals* to create block comments: literals* to create block comments:
.. code-block:: nimrod .. code-block:: nimrod
discard """ You can have any nimrod code text commented discard """ You can have any Nimrod code text commented
out inside this with no indentation restrictions. out inside this with no indentation restrictions.
yes("May I ask a pointless question?") """ yes("May I ask a pointless question?") """
@ -257,10 +258,10 @@ that can not be re-assigned, ``const`` means "enforce compile time evaluation
and put it into a data section": and put it into a data section":
.. code-block:: .. code-block::
const input = readline(stdin) # Error: constant expression expected const input = readLine(stdin) # Error: constant expression expected
.. code-block:: .. code-block::
let input = readline(stdin) # works let input = readLine(stdin) # works
Control flow statements Control flow statements
@ -285,9 +286,10 @@ The if statement is one way to branch the control flow:
else: else:
echo("Hi, ", name, "!") echo("Hi, ", name, "!")
There can be zero or more elif parts, and the else part is optional. The There can be zero or more ``elif`` parts, and the ``else`` part is optional.
keyword ``elif`` is short for ``else if``, and is useful to avoid excessive The keyword ``elif`` is short for ``else if``, and is useful to avoid
indentation. (The ``""`` is the empty string. It contains no characters.) excessive indentation. (The ``""`` is the empty string. It contains no
characters.)
Case statement Case statement
@ -338,7 +340,7 @@ the compiler that for every other value nothing should be done:
of 3, 8: echo("The number is 3 or 8") of 3, 8: echo("The number is 3 or 8")
else: discard else: discard
The empty ``discard`` statement is a *do nothing* statement. The compiler knows The empty `discard statement`_ is a *do nothing* statement. The compiler knows
that a case statement with an else part cannot fail and thus the error that a case statement with an else part cannot fail and thus the error
disappears. Note that it is impossible to cover all possible string values: disappears. Note that it is impossible to cover all possible string values:
that is why there is no such check for string cases. that is why there is no such check for string cases.
@ -370,7 +372,8 @@ For statement
------------- -------------
The ``for`` statement is a construct to loop over any element an *iterator* The ``for`` statement is a construct to loop over any element an *iterator*
provides. The example uses the built-in ``countup`` iterator: provides. The example uses the built-in `countup <system.html#countup>`_
iterator:
.. code-block:: nimrod .. code-block:: nimrod
echo("Counting to ten: ") echo("Counting to ten: ")
@ -378,11 +381,11 @@ provides. The example uses the built-in ``countup`` iterator:
echo($i) echo($i)
# --> Outputs 1 2 3 4 5 6 7 8 9 10 on different lines # --> Outputs 1 2 3 4 5 6 7 8 9 10 on different lines
The built-in ``$`` operator turns an integer (``int``) and many other types The built-in `$ <system.html#$>`_ operator turns an integer (``int``) and many
into a string. The variable ``i`` is implicitly declared by the ``for`` loop other types into a string. The variable ``i`` is implicitly declared by the
and has the type ``int``, because that is what ``countup`` returns. ``i`` runs ``for`` loop and has the type ``int``, because that is what `countup
through the values 1, 2, .., 10. Each value is ``echo``-ed. This code does <system.html#countup>`_ returns. ``i`` runs through the values 1, 2, .., 10.
the same: Each value is ``echo``-ed. This code does the same:
.. code-block:: nimrod .. code-block:: nimrod
echo("Counting to 10: ") echo("Counting to 10: ")
@ -400,8 +403,8 @@ Counting down can be achieved as easily (but is less often needed):
echo($i) echo($i)
# --> Outputs 10 9 8 7 6 5 4 3 2 1 on different lines # --> Outputs 10 9 8 7 6 5 4 3 2 1 on different lines
Since counting up occurs so often in programs, Nimrod also has a ``..`` iterator Since counting up occurs so often in programs, Nimrod also has a `..
that does the same: <system.html#...i,S,T>`_ iterator that does the same:
.. code-block:: nimrod .. code-block:: nimrod
for i in 1..10: for i in 1..10:
@ -553,9 +556,10 @@ an expression is allowed:
Procedures Procedures
========== ==========
To define new commands like ``echo``, ``readline`` in the examples, the concept To define new commands like `echo <system.html#echo>`_ and `readLine
of a `procedure` is needed. (Some languages call them *methods* or <system.html#readLine,TFile>`_ in the examples, the concept of a `procedure`
*functions*.) In Nimrod new procedures are defined with the ``proc`` keyword: is needed. (Some languages call them *methods* or *functions*.) In Nimrod new
procedures are defined with the ``proc`` keyword:
.. code-block:: nimrod .. code-block:: nimrod
proc yes(question: string): bool = proc yes(question: string): bool =
@ -649,7 +653,7 @@ a tuple as a return value instead of using var parameters.
Discard statement Discard statement
----------------- -----------------
To call a procedure that returns a value just for its side effects and ignoring To call a procedure that returns a value just for its side effects and ignoring
its return value, a discard statement **has** to be used. Nimrod does not its return value, a ``discard`` statement **has** to be used. Nimrod does not
allow to silently throw away a return value: allow to silently throw away a return value:
.. code-block:: nimrod .. code-block:: nimrod
@ -665,8 +669,8 @@ been declared with the ``discardable`` pragma:
p(3, 4) # now valid p(3, 4) # now valid
The discard statement can also be used to create block comments as described The ``discard`` statement can also be used to create block comments as
in the `Comments`_. described in the `Comments`_ section.
Named arguments Named arguments
@ -730,12 +734,12 @@ Nimrod provides the ability to overload procedures similar to C++:
echo(toString(13)) # calls the toString(x: int) proc echo(toString(13)) # calls the toString(x: int) proc
echo(toString(true)) # calls the toString(x: bool) proc echo(toString(true)) # calls the toString(x: bool) proc
(Note that ``toString`` is usually the ``$`` operator in Nimrod.) (Note that ``toString`` is usually the `$ <system.html#$>`_ operator in
The compiler chooses the most appropriate proc for the ``toString`` calls. How Nimrod.) The compiler chooses the most appropriate proc for the ``toString``
this overloading resolution algorithm works exactly is not discussed here calls. How this overloading resolution algorithm works exactly is not
(it will be specified in the manual soon). discussed here (it will be specified in the manual soon). However, it does
However, it does not lead to nasty surprises and is based on a quite simple not lead to nasty surprises and is based on a quite simple unification
unification algorithm. Ambiguous calls are reported as errors. algorithm. Ambiguous calls are reported as errors.
Operators Operators
@ -758,7 +762,7 @@ User defined operators are allowed. Nothing stops you from defining your own
The operator's precedence is determined by its first character. The details The operator's precedence is determined by its first character. The details
can be found in the manual. can be found in the manual.
To define a new operator enclose the operator in "``": To define a new operator enclose the operator in backticks "``":
.. code-block:: nimrod .. code-block:: nimrod
proc `$` (x: myDataType): string = ... proc `$` (x: myDataType): string = ...
@ -811,7 +815,8 @@ Let's return to the boring counting example:
for i in countup(1, 10): for i in countup(1, 10):
echo($i) echo($i)
Can a ``countup`` proc be written that supports this loop? Lets try: Can a `countup <system.html#countup>`_ proc be written that supports this
loop? Lets try:
.. code-block:: nimrod .. code-block:: nimrod
proc countup(a, b: int): int = proc countup(a, b: int): int =
@ -976,24 +981,25 @@ type:
The common operators ``+ - * / < <= == != > >=`` are defined for The common operators ``+ - * / < <= == != > >=`` are defined for
floats and follow the IEEE standard. floats and follow the IEEE standard.
Automatic type conversion in expressions with different kinds Automatic type conversion in expressions with different kinds of floating
of floating point types is performed: the smaller type is point types is performed: the smaller type is converted to the larger. Integer
converted to the larger. Integer types are **not** converted to floating point types are **not** converted to floating point types automatically and vice
types automatically and vice versa. The ``toInt`` and ``toFloat`` procs can be versa. The `toInt <system.html#toInt>`_ and `toFloat <system.html#toFloat>`_
used for these conversions. procs can be used for these conversions.
Internal type representation Internal type representation
============================ ============================
As mentioned earlier, the built-in ``$`` (stringify) operator turns any basic As mentioned earlier, the built-in `$ <system.html#$>`_ (stringify) operator
type into a string, which you can then print to the screen with the ``echo`` turns any basic type into a string, which you can then print to the screen
proc. However, advanced types, or types you may define yourself won't work with with the ``echo`` proc. However, advanced types, or types you may define
the ``$`` operator until you define one for them. Sometimes you just want to yourself won't work with the ``$`` operator until you define one for them.
debug the current value of a complex type without having to write its ``$`` Sometimes you just want to debug the current value of a complex type without
operator. You can use then the ``repr`` proc which works with any type and having to write its ``$`` operator. You can use then the `repr
even complex data graphs with cycles. The following example shows that even for <system.html#repr>`_ proc which works with any type and even complex data
basic types there is a difference between the ``$`` and ``repr`` outputs: graphs with cycles. The following example shows that even for basic types
there is a difference between the ``$`` and ``repr`` outputs:
.. code-block:: nimrod .. code-block:: nimrod
var var
@ -1087,9 +1093,10 @@ Operation Comment
``pred(x, n)`` returns the `n`'th predecessor of `x` ``pred(x, n)`` returns the `n`'th predecessor of `x`
----------------- -------------------------------------------------------- ----------------- --------------------------------------------------------
The ``inc dec succ pred`` operations can fail by raising an `EOutOfRange` or The `inc <system.html#inc>`_, `dec <system.html#dec>`_, `succ
`EOverflow` exception. (If the code has been compiled with the proper runtime <system.html#succ>`_ and `pred <system.html#pred>`_ operations can fail by
checks turned on.) raising an `EOutOfRange` or `EOverflow` exception. (If the code has been
compiled with the proper runtime checks turned on.)
Subranges Subranges
@ -1107,12 +1114,12 @@ to 5. Assigning any other value to a variable of type ``TSubrange`` is a
compile-time or runtime error. Assignments from the base type to one of its compile-time or runtime error. Assignments from the base type to one of its
subrange types (and vice versa) are allowed. subrange types (and vice versa) are allowed.
The ``system`` module defines the important ``natural`` type as The ``system`` module defines the important `Natural <system.html#Natural>`_
``range[0..high(int)]`` (``high`` returns the maximal value). Other programming type as ``range[0..high(int)]`` (`high <system.html#high>`_ returns the
languages mandate the usage of unsigned integers for natural numbers. This is maximal value). Other programming languages mandate the usage of unsigned
often **wrong**: you don't want unsigned arithmetic (which wraps around) just integers for natural numbers. This is often **wrong**: you don't want unsigned
because the numbers cannot be negative. Nimrod's ``natural`` type helps to arithmetic (which wraps around) just because the numbers cannot be negative.
avoid this common programming error. Nimrod's ``Natural`` type helps to avoid this common programming error.
Sets Sets
@ -1145,8 +1152,9 @@ checks can be disabled via pragmas or invoking the compiler with the
Arrays are value types, like any other Nimrod type. The assignment operator Arrays are value types, like any other Nimrod type. The assignment operator
copies the whole array contents. copies the whole array contents.
The built-in ``len`` proc returns the array's length. ``low(a)`` returns the The built-in `len <system.html#len,TOpenArray>`_ proc returns the array's
lowest valid index for the array `a` and ``high(a)`` the highest valid index. length. `low(a) <system.html#low>`_ returns the lowest valid index for the
array `a` and `high(a) <system.html#high>`_ the highest valid index.
.. code-block:: nimrod .. code-block:: nimrod
type type
@ -1218,13 +1226,14 @@ Sequences are similar to arrays but of dynamic length which may change
during runtime (like strings). Since sequences are resizable they are always during runtime (like strings). Since sequences are resizable they are always
allocated on the heap and garbage collected. allocated on the heap and garbage collected.
Sequences are always indexed with an ``int`` starting at position 0. Sequences are always indexed with an ``int`` starting at position 0. The `len
The ``len``, ``low`` and ``high`` operations are available for sequences too. <system.html#len,seq[T]>`_, `low <system.html#low>`_ and `high
The notation ``x[i]`` can be used to access the i-th element of ``x``. <system.html#high>`_ operations are available for sequences too. The notation
``x[i]`` can be used to access the i-th element of ``x``.
Sequences can be constructed by the array constructor ``[]`` in conjunction Sequences can be constructed by the array constructor ``[]`` in conjunction
with the array to sequence operator ``@``. Another way to allocate space for with the array to sequence operator ``@``. Another way to allocate space for
a sequence is to call the built-in ``newSeq`` procedure. a sequence is to call the built-in `newSeq <system.html#newSeq>`_ procedure.
A sequence may be passed to an openarray parameter. A sequence may be passed to an openarray parameter.
@ -1245,10 +1254,11 @@ object on the heap, so there is a trade-off to be made here.
The ``for`` statement can be used with one or two variables when used with a The ``for`` statement can be used with one or two variables when used with a
sequence. When you use the one variable form, the variable will hold the value sequence. When you use the one variable form, the variable will hold the value
provided by the sequence. The ``for`` statement is looping over the results provided by the sequence. The ``for`` statement is looping over the results
from the ``items()`` iterator from the `system <system.html>`_ module. But if from the `items() <system.html#items.i,seq[T]>`_ iterator from the `system
you use the two variable form, the first variable will hold the index position <system.html>`_ module. But if you use the two variable form, the first
and the second variable will hold the value. Here the ``for`` statement is variable will hold the index position and the second variable will hold the
looping over the results from the ``pairs()`` iterator from the `system value. Here the ``for`` statement is looping over the results from the
`pairs() <system.html#pairs.i,seq[T]>`_ iterator from the `system
<system.html>`_ module. Examples: <system.html>`_ module. Examples:
.. code-block:: nimrod .. code-block:: nimrod
@ -1269,12 +1279,13 @@ Open arrays
----------- -----------
**Note**: Openarrays can only be used for parameters. **Note**: Openarrays can only be used for parameters.
Often fixed size arrays turn out to be too inflexible; procedures should Often fixed size arrays turn out to be too inflexible; procedures should be
be able to deal with arrays of different sizes. The `openarray`:idx: type able to deal with arrays of different sizes. The `openarray`:idx: type allows
allows this. Openarrays are always indexed with an ``int`` starting at this. Openarrays are always indexed with an ``int`` starting at position 0.
position 0. The ``len``, ``low`` and ``high`` operations are available The `len <system.html#len,TOpenArray>`_, `low <system.html#low>`_ and `high
for open arrays too. Any array with a compatible base type can be passed to <system.html#high>`_ operations are available for open arrays too. Any array
an openarray parameter, the index type does not matter. with a compatible base type can be passed to an openarray parameter, the index
type does not matter.
The openarray type cannot be nested: multidimensional openarrays are not The openarray type cannot be nested: multidimensional openarrays are not
supported because this is seldom needed and cannot be done efficiently. supported because this is seldom needed and cannot be done efficiently.
@ -1312,8 +1323,9 @@ type conversions in this context:
# is transformed by the compiler to: # is transformed by the compiler to:
myWriteln(stdout, [$123, $"def", $4.0]) myWriteln(stdout, [$123, $"def", $4.0])
In this example ``$`` is applied to any argument that is passed to the In this example `$ <system.html#$>`_ is applied to any argument that is passed
parameter ``a``. Note that ``$`` applied to strings is a nop. to the parameter ``a``. Note that `$ <system.html#$>`_ applied to strings is a
nop.
Slices Slices
@ -1392,11 +1404,12 @@ having the same field types.
Tuples can be *unpacked* during variable assignment (and only then!). This can Tuples can be *unpacked* during variable assignment (and only then!). This can
be handy to assign directly the fields of the tuples to individually named be handy to assign directly the fields of the tuples to individually named
variables. An example of this is the ``splitFile`` proc from the `os module variables. An example of this is the `splitFile <os.html#splitFile>`_ proc
<os.html>`_ which returns the directory, name and extension of a path at the from the `os module <os.html>`_ which returns the directory, name and
same time. For tuple unpacking to work you have to use parenthesis around the extension of a path at the same time. For tuple unpacking to work you have to
values you want to assign the unpacking to, otherwise you will be assigning the use parenthesis around the values you want to assign the unpacking to,
same value to all the individual variables! Example: otherwise you will be assigning the same value to all the individual
variables! Example:
.. code-block:: nimrod .. code-block:: nimrod