tut1.rst 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842
  1. =====================
  2. Nim Tutorial (Part I)
  3. =====================
  4. :Author: Andreas Rumpf
  5. :Version: |nimversion|
  6. .. contents::
  7. Introduction
  8. ============
  9. .. raw:: html
  10. <blockquote><p>
  11. "Der Mensch ist doch ein Augentier -- sch&ouml;ne Dinge w&uuml;nsch ich mir."
  12. </p></blockquote>
  13. This document is a tutorial for the programming language *Nim*.
  14. This tutorial assumes that you are familiar with basic programming concepts
  15. like variables, types, or statements but is kept very basic. The `manual
  16. <manual.html>`_ contains many more examples of the advanced language features.
  17. All code examples in this tutorial, as well as the ones found in the rest of
  18. Nim's documentation, follow the `Nim style guide <nep1.html>`_.
  19. The first program
  20. =================
  21. We start the tour with a modified "hello world" program:
  22. .. code-block:: Nim
  23. :test: "nim c $1"
  24. # This is a comment
  25. echo "What's your name? "
  26. var name: string = readLine(stdin)
  27. echo "Hi, ", name, "!"
  28. Save this code to the file "greetings.nim". Now compile and run it::
  29. nim compile --run greetings.nim
  30. With the ``--run`` `switch <nimc.html#compiler-usage-commandminusline-switches>`_ Nim
  31. executes the file automatically after compilation. You can give your program
  32. command-line arguments by appending them after the filename::
  33. nim compile --run greetings.nim arg1 arg2
  34. Commonly used commands and switches have abbreviations, so you can also use::
  35. nim c -r greetings.nim
  36. To compile a release version use::
  37. nim c -d:release greetings.nim
  38. By default, the Nim compiler generates a large number of runtime checks
  39. aiming for your debugging pleasure. With ``-d:release`` some checks are
  40. `turned off and optimizations are turned on
  41. <nimc.html#compiler-usage-compileminustime-symbols>`_.
  42. Though it should be pretty obvious what the program does, I will explain the
  43. syntax: statements which are not indented are executed when the program
  44. starts. Indentation is Nim's way of grouping statements. Indentation is
  45. done with spaces only, tabulators are not allowed.
  46. String literals are enclosed in double-quotes. The ``var`` statement declares
  47. a new variable named ``name`` of type ``string`` with the value that is
  48. returned by the `readLine <io.html#readLine,File>`_ procedure. Since the
  49. compiler knows that `readLine <io.html#readLine,File>`_ returns a string,
  50. you can leave out the type in the declaration (this is called `local type
  51. inference`:idx:). So this will work too:
  52. .. code-block:: Nim
  53. :test: "nim c $1"
  54. var name = readLine(stdin)
  55. Note that this is basically the only form of type inference that exists in
  56. Nim: it is a good compromise between brevity and readability.
  57. The "hello world" program contains several identifiers that are already known
  58. to the compiler: ``echo``, `readLine <io.html#readLine,File>`_, etc.
  59. These built-ins are declared in the system_ module which is implicitly
  60. imported by any other module.
  61. Lexical elements
  62. ================
  63. Let us look at Nim's lexical elements in more detail: like other
  64. programming languages Nim consists of (string) literals, identifiers,
  65. keywords, comments, operators, and other punctuation marks.
  66. String and character literals
  67. -----------------------------
  68. String literals are enclosed in double-quotes; character literals in single
  69. quotes. Special characters are escaped with ``\``: ``\n`` means newline, ``\t``
  70. means tabulator, etc. There are also *raw* string literals:
  71. .. code-block:: Nim
  72. r"C:\program files\nim"
  73. In raw literals, the backslash is not an escape character.
  74. The third and last way to write string literals is *long-string literals*.
  75. They are written with three quotes: ``""" ... """``; they can span over
  76. multiple lines and the ``\`` is not an escape character either. They are very
  77. useful for embedding HTML code templates for example.
  78. Comments
  79. --------
  80. Comments start anywhere outside a string or character literal with the
  81. hash character ``#``. Documentation comments start with ``##``:
  82. .. code-block:: nim
  83. :test: "nim c $1"
  84. # A comment.
  85. var myVariable: int ## a documentation comment
  86. Documentation comments are tokens; they are only allowed at certain places in
  87. the input file as they belong to the syntax tree! This feature enables simpler
  88. documentation generators.
  89. Multiline comments are started with ``#[`` and terminated with ``]#``. Multiline
  90. comments can also be nested.
  91. .. code-block:: nim
  92. :test: "nim c $1"
  93. #[
  94. You can have any Nim code text commented
  95. out inside this with no indentation restrictions.
  96. yes("May I ask a pointless question?")
  97. #[
  98. Note: these can be nested!!
  99. ]#
  100. ]#
  101. Numbers
  102. -------
  103. Numerical literals are written as in most other languages. As a special twist,
  104. underscores are allowed for better readability: ``1_000_000`` (one million).
  105. A number that contains a dot (or 'e' or 'E') is a floating-point literal:
  106. ``1.0e9`` (one billion). Hexadecimal literals are prefixed with ``0x``,
  107. binary literals with ``0b`` and octal literals with ``0o``. A leading zero
  108. alone does not produce an octal.
  109. The var statement
  110. =================
  111. The var statement declares a new local or global variable:
  112. .. code-block::
  113. var x, y: int # declares x and y to have the type ``int``
  114. Indentation can be used after the ``var`` keyword to list a whole section of
  115. variables:
  116. .. code-block::
  117. :test: "nim c $1"
  118. var
  119. x, y: int
  120. # a comment can occur here too
  121. a, b, c: string
  122. The assignment statement
  123. ========================
  124. The assignment statement assigns a new value to a variable or more generally
  125. to a storage location:
  126. .. code-block::
  127. var x = "abc" # introduces a new variable `x` and assigns a value to it
  128. x = "xyz" # assigns a new value to `x`
  129. ``=`` is the *assignment operator*. The assignment operator can be
  130. overloaded. You can declare multiple variables with a single assignment
  131. statement and all the variables will have the same value:
  132. .. code-block::
  133. :test: "nim c $1"
  134. var x, y = 3 # assigns 3 to the variables `x` and `y`
  135. echo "x ", x # outputs "x 3"
  136. echo "y ", y # outputs "y 3"
  137. x = 42 # changes `x` to 42 without changing `y`
  138. echo "x ", x # outputs "x 42"
  139. echo "y ", y # outputs "y 3"
  140. Note that declaring multiple variables with a single assignment that calls a
  141. procedure can have unexpected results: the compiler will *unroll* the
  142. assignments and end up calling the procedure several times. If the result of
  143. the procedure depends on side effects, your variables may end up having
  144. different values! For safety use side-effect-free procedures if making multiple
  145. assignments.
  146. Constants
  147. =========
  148. Constants are symbols which are bound to a value. The constant's value
  149. cannot change. The compiler must be able to evaluate the expression in a
  150. constant declaration at compile time:
  151. .. code-block:: nim
  152. :test: "nim c $1"
  153. const x = "abc" # the constant x contains the string "abc"
  154. Indentation can be used after the ``const`` keyword to list a whole section of
  155. constants:
  156. .. code-block::
  157. :test: "nim c $1"
  158. const
  159. x = 1
  160. # a comment can occur here too
  161. y = 2
  162. z = y + 5 # computations are possible
  163. The let statement
  164. =================
  165. The ``let`` statement works like the ``var`` statement but the declared
  166. symbols are *single assignment* variables: After the initialization their
  167. value cannot change:
  168. .. code-block::
  169. let x = "abc" # introduces a new variable `x` and binds a value to it
  170. x = "xyz" # Illegal: assignment to `x`
  171. The difference between ``let`` and ``const`` is: ``let`` introduces a variable
  172. that can not be re-assigned, ``const`` means "enforce compile time evaluation
  173. and put it into a data section":
  174. .. code-block::
  175. const input = readLine(stdin) # Error: constant expression expected
  176. .. code-block::
  177. :test: "nim c $1"
  178. let input = readLine(stdin) # works
  179. Control flow statements
  180. =======================
  181. The greetings program consists of 3 statements that are executed sequentially.
  182. Only the most primitive programs can get away with that: branching and looping
  183. are needed too.
  184. If statement
  185. ------------
  186. The if statement is one way to branch the control flow:
  187. .. code-block:: nim
  188. :test: "nim c $1"
  189. let name = readLine(stdin)
  190. if name == "":
  191. echo "Poor soul, you lost your name?"
  192. elif name == "name":
  193. echo "Very funny, your name is name."
  194. else:
  195. echo "Hi, ", name, "!"
  196. There can be zero or more ``elif`` parts, and the ``else`` part is optional.
  197. The keyword ``elif`` is short for ``else if``, and is useful to avoid
  198. excessive indentation. (The ``""`` is the empty string. It contains no
  199. characters.)
  200. Case statement
  201. --------------
  202. Another way to branch is provided by the case statement. A case statement is
  203. a multi-branch:
  204. .. code-block:: nim
  205. :test: "nim c $1"
  206. let name = readLine(stdin)
  207. case name
  208. of "":
  209. echo "Poor soul, you lost your name?"
  210. of "name":
  211. echo "Very funny, your name is name."
  212. of "Dave", "Frank":
  213. echo "Cool name!"
  214. else:
  215. echo "Hi, ", name, "!"
  216. As it can be seen, for an ``of`` branch a comma-separated list of values is also
  217. allowed.
  218. The case statement can deal with integers, other ordinal types, and strings.
  219. (What an ordinal type is will be explained soon.)
  220. For integers or other ordinal types value ranges are also possible:
  221. .. code-block:: nim
  222. # this statement will be explained later:
  223. from strutils import parseInt
  224. echo "A number please: "
  225. let n = parseInt(readLine(stdin))
  226. case n
  227. of 0..2, 4..7: echo "The number is in the set: {0, 1, 2, 4, 5, 6, 7}"
  228. of 3, 8: echo "The number is 3 or 8"
  229. However, the above code does not compile: the reason is that you have to cover
  230. every value that ``n`` may contain, but the code only handles the values
  231. ``0..8``. Since it is not very practical to list every other possible integer
  232. (though it is possible thanks to the range notation), we fix this by telling
  233. the compiler that for every other value nothing should be done:
  234. .. code-block:: nim
  235. ...
  236. case n
  237. of 0..2, 4..7: echo "The number is in the set: {0, 1, 2, 4, 5, 6, 7}"
  238. of 3, 8: echo "The number is 3 or 8"
  239. else: discard
  240. The empty `discard statement <#procedures-discard-statement>`_ is a *do
  241. nothing* statement. The compiler knows that a case statement with an else part
  242. cannot fail and thus the error disappears. Note that it is impossible to cover
  243. all possible string values: that is why string cases always need an ``else``
  244. branch.
  245. In general, the case statement is used for subrange types or enumerations where
  246. it is of great help that the compiler checks that you covered any possible
  247. value.
  248. While statement
  249. ---------------
  250. The while statement is a simple looping construct:
  251. .. code-block:: nim
  252. :test: "nim c $1"
  253. echo "What's your name? "
  254. var name = readLine(stdin)
  255. while name == "":
  256. echo "Please tell me your name: "
  257. name = readLine(stdin)
  258. # no ``var``, because we do not declare a new variable here
  259. The example uses a while loop to keep asking the users for their name, as long
  260. as the user types in nothing (only presses RETURN).
  261. For statement
  262. -------------
  263. The ``for`` statement is a construct to loop over any element an *iterator*
  264. provides. The example uses the built-in `countup
  265. <system.html#countup.i,T,T,Positive>`_ iterator:
  266. .. code-block:: nim
  267. :test: "nim c $1"
  268. echo "Counting to ten: "
  269. for i in countup(1, 10):
  270. echo i
  271. # --> Outputs 1 2 3 4 5 6 7 8 9 10 on different lines
  272. The variable ``i`` is implicitly declared by the
  273. ``for`` loop and has the type ``int``, because that is what `countup
  274. <system.html#countup.i,T,T,Positive>`_ returns. ``i`` runs through the values
  275. 1, 2, .., 10. Each value is ``echo``-ed. This code does the same:
  276. .. code-block:: nim
  277. echo "Counting to 10: "
  278. var i = 1
  279. while i <= 10:
  280. echo i
  281. inc(i) # increment i by 1
  282. # --> Outputs 1 2 3 4 5 6 7 8 9 10 on different lines
  283. Counting down can be achieved as easily (but is less often needed):
  284. .. code-block:: nim
  285. echo "Counting down from 10 to 1: "
  286. for i in countdown(10, 1):
  287. echo i
  288. # --> Outputs 10 9 8 7 6 5 4 3 2 1 on different lines
  289. Since counting up occurs so often in programs, Nim also has a `..
  290. <system.html#...i,T,T>`_ iterator that does the same:
  291. .. code-block:: nim
  292. for i in 1 .. 10:
  293. ...
  294. Zero-indexed counting has two shortcuts ``..<`` and ``.. ^1``
  295. (`backward index operator <system.html#^.t%2Cint>`_) to simplify
  296. counting to one less than the higher index:
  297. .. code-block:: nim
  298. for i in 0 ..< 10:
  299. ... # 0 .. 9
  300. or
  301. .. code-block:: nim
  302. var s = "some string"
  303. for i in 0 ..< s.len:
  304. ...
  305. or
  306. .. code-block:: nim
  307. var s = "some string"
  308. for idx, c in s[0 .. ^1]:
  309. ...
  310. Other useful iterators for collections (like arrays and sequences) are
  311. * ``items`` and ``mitems``, which provides immutable and mutable elements respectively, and
  312. * ``pairs`` and ``mpairs`` which provides the element and an index number (immutable and mutable respectively)
  313. .. code-block:: nim
  314. :test: "nim c $1"
  315. for index, item in ["a","b"].pairs:
  316. echo item, " at index ", index
  317. # => a at index 0
  318. # => b at index 1
  319. Scopes and the block statement
  320. ------------------------------
  321. Control flow statements have a feature not covered yet: they open a
  322. new scope. This means that in the following example, ``x`` is not accessible
  323. outside the loop:
  324. .. code-block:: nim
  325. :test: "nim c $1"
  326. :status: 1
  327. while false:
  328. var x = "hi"
  329. echo x # does not work
  330. A while (for) statement introduces an implicit block. Identifiers
  331. are only visible within the block they have been declared. The ``block``
  332. statement can be used to open a new block explicitly:
  333. .. code-block:: nim
  334. :test: "nim c $1"
  335. :status: 1
  336. block myblock:
  337. var x = "hi"
  338. echo x # does not work either
  339. The block's *label* (``myblock`` in the example) is optional.
  340. Break statement
  341. ---------------
  342. A block can be left prematurely with a ``break`` statement. The break statement
  343. can leave a ``while``, ``for``, or a ``block`` statement. It leaves the
  344. innermost construct, unless a label of a block is given:
  345. .. code-block:: nim
  346. :test: "nim c $1"
  347. block myblock:
  348. echo "entering block"
  349. while true:
  350. echo "looping"
  351. break # leaves the loop, but not the block
  352. echo "still in block"
  353. echo "outside the block"
  354. block myblock2:
  355. echo "entering block"
  356. while true:
  357. echo "looping"
  358. break myblock2 # leaves the block (and the loop)
  359. echo "still in block" # it won't be printed
  360. echo "outside the block"
  361. Continue statement
  362. ------------------
  363. Like in many other programming languages, a ``continue`` statement starts
  364. the next iteration immediately:
  365. .. code-block:: nim
  366. :test: "nim c $1"
  367. while true:
  368. let x = readLine(stdin)
  369. if x == "": continue
  370. echo x
  371. When statement
  372. --------------
  373. Example:
  374. .. code-block:: nim
  375. :test: "nim c $1"
  376. when system.hostOS == "windows":
  377. echo "running on Windows!"
  378. elif system.hostOS == "linux":
  379. echo "running on Linux!"
  380. elif system.hostOS == "macosx":
  381. echo "running on Mac OS X!"
  382. else:
  383. echo "unknown operating system"
  384. The ``when`` statement is almost identical to the ``if`` statement, but with these
  385. differences:
  386. * Each condition must be a constant expression since it is evaluated by the
  387. compiler.
  388. * The statements within a branch do not open a new scope.
  389. * The compiler checks the semantics and produces code *only* for the statements
  390. that belong to the first condition that evaluates to ``true``.
  391. The ``when`` statement is useful for writing platform-specific code, similar to
  392. the ``#ifdef`` construct in the C programming language.
  393. Statements and indentation
  394. ==========================
  395. Now that we covered the basic control flow statements, let's return to Nim
  396. indentation rules.
  397. In Nim, there is a distinction between *simple statements* and *complex
  398. statements*. *Simple statements* cannot contain other statements:
  399. Assignment, procedure calls, or the ``return`` statement are all simple
  400. statements. *Complex statements* like ``if``, ``when``, ``for``, ``while`` can
  401. contain other statements. To avoid ambiguities, complex statements must always
  402. be indented, but single simple statements do not:
  403. .. code-block:: nim
  404. # no indentation needed for single-assignment statement:
  405. if x: x = false
  406. # indentation needed for nested if statement:
  407. if x:
  408. if y:
  409. y = false
  410. else:
  411. y = true
  412. # indentation needed, because two statements follow the condition:
  413. if x:
  414. x = false
  415. y = false
  416. *Expressions* are parts of a statement that usually result in a value. The
  417. condition in an if statement is an example of an expression. Expressions can
  418. contain indentation at certain places for better readability:
  419. .. code-block:: nim
  420. if thisIsaLongCondition() and
  421. thisIsAnotherLongCondition(1,
  422. 2, 3, 4):
  423. x = true
  424. As a rule of thumb, indentation within expressions is allowed after operators,
  425. an open parenthesis and after commas.
  426. With parenthesis and semicolons ``(;)`` you can use statements where only
  427. an expression is allowed:
  428. .. code-block:: nim
  429. :test: "nim c $1"
  430. # computes fac(4) at compile time:
  431. const fac4 = (var x = 1; for i in 1..4: x *= i; x)
  432. Procedures
  433. ==========
  434. To define new commands like `echo <system.html#echo,varargs[typed,]>`_
  435. and `readLine <io.html#readLine,File>`_ in the examples, the concept of a
  436. `procedure` is needed. (Some languages call them *methods* or *functions*.)
  437. In Nim new procedures are defined with the ``proc`` keyword:
  438. .. code-block:: nim
  439. :test: "nim c $1"
  440. proc yes(question: string): bool =
  441. echo question, " (y/n)"
  442. while true:
  443. case readLine(stdin)
  444. of "y", "Y", "yes", "Yes": return true
  445. of "n", "N", "no", "No": return false
  446. else: echo "Please be clear: yes or no"
  447. if yes("Should I delete all your important files?"):
  448. echo "I'm sorry Dave, I'm afraid I can't do that."
  449. else:
  450. echo "I think you know what the problem is just as well as I do."
  451. This example shows a procedure named ``yes`` that asks the user a ``question``
  452. and returns true if they answered "yes" (or something similar) and returns
  453. false if they answered "no" (or something similar). A ``return`` statement
  454. leaves the procedure (and therefore the while loop) immediately. The
  455. ``(question: string): bool`` syntax describes that the procedure expects a
  456. parameter named ``question`` of type ``string`` and returns a value of type
  457. ``bool``. The ``bool`` type is built-in: the only valid values for ``bool`` are
  458. ``true`` and ``false``.
  459. The conditions in if or while statements must be of type ``bool``.
  460. Some terminology: in the example ``question`` is called a (formal) *parameter*,
  461. ``"Should I..."`` is called an *argument* that is passed to this parameter.
  462. Result variable
  463. ---------------
  464. A procedure that returns a value has an implicit ``result`` variable declared
  465. that represents the return value. A ``return`` statement with no expression is
  466. shorthand for ``return result``. The ``result`` value is always returned
  467. automatically at the end of a procedure if there is no ``return`` statement at
  468. the exit.
  469. .. code-block:: nim
  470. :test: "nim c $1"
  471. proc sumTillNegative(x: varargs[int]): int =
  472. for i in x:
  473. if i < 0:
  474. return
  475. result = result + i
  476. echo sumTillNegative() # echos 0
  477. echo sumTillNegative(3, 4, 5) # echos 12
  478. echo sumTillNegative(3, 4 , -1 , 6) # echos 7
  479. The ``result`` variable is already implicitly declared at the start of the
  480. function, so declaring it again with 'var result', for example, would shadow it
  481. with a normal variable of the same name. The result variable is also already
  482. initialized with the type's default value. Note that referential data types will
  483. be ``nil`` at the start of the procedure, and thus may require manual
  484. initialization.
  485. A procedure that does not have any ``return`` statement and does not use the
  486. special ``result`` variable returns the value of its last expression. For example,
  487. this procedure
  488. .. code-block:: nim
  489. :test: "nim c $1"
  490. proc helloWorld(): string =
  491. "Hello, World!"
  492. returns the string "Hello, World!".
  493. Parameters
  494. ----------
  495. Parameters are immutable in the procedure body. By default, their value cannot be
  496. changed because this allows the compiler to implement parameter passing in the
  497. most efficient way. If a mutable variable is needed inside the procedure, it has
  498. to be declared with ``var`` in the procedure body. Shadowing the parameter name
  499. is possible, and actually an idiom:
  500. .. code-block:: nim
  501. :test: "nim c $1"
  502. proc printSeq(s: seq, nprinted: int = -1) =
  503. var nprinted = if nprinted == -1: s.len else: min(nprinted, s.len)
  504. for i in 0 ..< nprinted:
  505. echo s[i]
  506. If the procedure needs to modify the argument for the
  507. caller, a ``var`` parameter can be used:
  508. .. code-block:: nim
  509. :test: "nim c $1"
  510. proc divmod(a, b: int; res, remainder: var int) =
  511. res = a div b # integer division
  512. remainder = a mod b # integer modulo operation
  513. var
  514. x, y: int
  515. divmod(8, 5, x, y) # modifies x and y
  516. echo x
  517. echo y
  518. In the example, ``res`` and ``remainder`` are `var parameters`.
  519. Var parameters can be modified by the procedure and the changes are
  520. visible to the caller. Note that the above example would better make use of
  521. a tuple as a return value instead of using var parameters.
  522. Discard statement
  523. -----------------
  524. To call a procedure that returns a value just for its side effects and ignoring
  525. its return value, a ``discard`` statement **must** be used. Nim does not
  526. allow silently throwing away a return value:
  527. .. code-block:: nim
  528. discard yes("May I ask a pointless question?")
  529. The return value can be ignored implicitly if the called proc/iterator has
  530. been declared with the ``discardable`` pragma:
  531. .. code-block:: nim
  532. :test: "nim c $1"
  533. proc p(x, y: int): int {.discardable.} =
  534. return x + y
  535. p(3, 4) # now valid
  536. Named arguments
  537. ---------------
  538. Often a procedure has many parameters and it is not clear in which order the
  539. parameters appear. This is especially true for procedures that construct a
  540. complex data type. Therefore the arguments to a procedure can be named, so
  541. that it is clear which argument belongs to which parameter:
  542. .. code-block:: nim
  543. proc createWindow(x, y, width, height: int; title: string;
  544. show: bool): Window =
  545. ...
  546. var w = createWindow(show = true, title = "My Application",
  547. x = 0, y = 0, height = 600, width = 800)
  548. Now that we use named arguments to call ``createWindow`` the argument order
  549. does not matter anymore. Mixing named arguments with ordered arguments is
  550. also possible, but not very readable:
  551. .. code-block:: nim
  552. var w = createWindow(0, 0, title = "My Application",
  553. height = 600, width = 800, true)
  554. The compiler checks that each parameter receives exactly one argument.
  555. Default values
  556. --------------
  557. To make the ``createWindow`` proc easier to use it should provide `default
  558. values`; these are values that are used as arguments if the caller does not
  559. specify them:
  560. .. code-block:: nim
  561. proc createWindow(x = 0, y = 0, width = 500, height = 700,
  562. title = "unknown",
  563. show = true): Window =
  564. ...
  565. var w = createWindow(title = "My Application", height = 600, width = 800)
  566. Now the call to ``createWindow`` only needs to set the values that differ
  567. from the defaults.
  568. Note that type inference works for parameters with default values; there is
  569. no need to write ``title: string = "unknown"``, for example.
  570. Overloaded procedures
  571. ---------------------
  572. Nim provides the ability to overload procedures similar to C++:
  573. .. code-block:: nim
  574. proc toString(x: int): string =
  575. result =
  576. if x < 0: "negative"
  577. elif x > 0: "positive"
  578. else: "zero"
  579. proc toString(x: bool): string =
  580. result =
  581. if x: "yep"
  582. else: "nope"
  583. assert toString(13) == "positive" # calls the toString(x: int) proc
  584. assert toString(true) == "yep" # calls the toString(x: bool) proc
  585. (Note that ``toString`` is usually the `$ <dollars.html>`_ operator in
  586. Nim.) The compiler chooses the most appropriate proc for the ``toString``
  587. calls. How this overloading resolution algorithm works exactly is not
  588. discussed here (it will be specified in the manual soon). However, it does
  589. not lead to nasty surprises and is based on a quite simple unification
  590. algorithm. Ambiguous calls are reported as errors.
  591. Operators
  592. ---------
  593. The Nim library makes heavy use of overloading - one reason for this is that
  594. each operator like ``+`` is just an overloaded proc. The parser lets you
  595. use operators in `infix notation` (``a + b``) or `prefix notation` (``+ a``).
  596. An infix operator always receives two arguments, a prefix operator always one.
  597. (Postfix operators are not possible, because this would be ambiguous: does
  598. ``a @ @ b`` mean ``(a) @ (@b)`` or ``(a@) @ (b)``? It always means
  599. ``(a) @ (@b)``, because there are no postfix operators in Nim.)
  600. Apart from a few built-in keyword operators such as ``and``, ``or``, ``not``,
  601. operators always consist of these characters:
  602. ``+ - * \ / < > = @ $ ~ & % ! ? ^ . |``
  603. User-defined operators are allowed. Nothing stops you from defining your own
  604. ``@!?+~`` operator, but doing so may reduce readability.
  605. The operator's precedence is determined by its first character. The details
  606. can be found in the manual.
  607. To define a new operator enclose the operator in backticks "``":
  608. .. code-block:: nim
  609. proc `$` (x: myDataType): string = ...
  610. # now the $ operator also works with myDataType, overloading resolution
  611. # ensures that $ works for built-in types just like before
  612. The "``" notation can also be used to call an operator just like any other
  613. procedure:
  614. .. code-block:: nim
  615. :test: "nim c $1"
  616. if `==`( `+`(3, 4), 7): echo "True"
  617. Forward declarations
  618. --------------------
  619. Every variable, procedure, etc. needs to be declared before it can be used.
  620. (The reason for this is that it is non-trivial to avoid this need in a
  621. language that supports metaprogramming as extensively as Nim does.)
  622. However, this cannot be done for mutually recursive procedures:
  623. .. code-block:: nim
  624. # forward declaration:
  625. proc even(n: int): bool
  626. .. code-block:: nim
  627. proc odd(n: int): bool =
  628. assert(n >= 0) # makes sure we don't run into negative recursion
  629. if n == 0: false
  630. else:
  631. n == 1 or even(n-1)
  632. proc even(n: int): bool =
  633. assert(n >= 0) # makes sure we don't run into negative recursion
  634. if n == 1: false
  635. else:
  636. n == 0 or odd(n-1)
  637. Here ``odd`` depends on ``even`` and vice versa. Thus ``even`` needs to be
  638. introduced to the compiler before it is completely defined. The syntax for
  639. such a forward declaration is simple: just omit the ``=`` and the
  640. procedure's body. The ``assert`` just adds border conditions, and will be
  641. covered later in `Modules`_ section.
  642. Later versions of the language will weaken the requirements for forward
  643. declarations.
  644. The example also shows that a proc's body can consist of a single expression
  645. whose value is then returned implicitly.
  646. Iterators
  647. =========
  648. Let's return to the simple counting example:
  649. .. code-block:: nim
  650. :test: "nim c $1"
  651. echo "Counting to ten: "
  652. for i in countup(1, 10):
  653. echo i
  654. Can a `countup <system.html#countup.i,T,T,Positive>`_ proc be written that
  655. supports this loop? Lets try:
  656. .. code-block:: nim
  657. proc countup(a, b: int): int =
  658. var res = a
  659. while res <= b:
  660. return res
  661. inc(res)
  662. However, this does not work. The problem is that the procedure should not
  663. only ``return``, but return and **continue** after an iteration has
  664. finished. This *return and continue* is called a `yield` statement. Now
  665. the only thing left to do is to replace the ``proc`` keyword by ``iterator``
  666. and here it is - our first iterator:
  667. .. code-block:: nim
  668. :test: "nim c $1"
  669. iterator countup(a, b: int): int =
  670. var res = a
  671. while res <= b:
  672. yield res
  673. inc(res)
  674. Iterators look very similar to procedures, but there are several
  675. important differences:
  676. * Iterators can only be called from for loops.
  677. * Iterators cannot contain a ``return`` statement (and procs cannot contain a
  678. ``yield`` statement).
  679. * Iterators have no implicit ``result`` variable.
  680. * Iterators do not support recursion.
  681. * Iterators cannot be forward declared, because the compiler must be able to inline an iterator. (This restriction will be gone in a
  682. future version of the compiler.)
  683. However, you can also use a ``closure`` iterator to get a different set of
  684. restrictions. See `first-class iterators <manual.html#iterators-and-the-for-statement-firstminusclass-iterators>`_
  685. for details. Iterators can have the same name and parameters as a proc since
  686. essentially they have their own namespaces. Therefore it is common practice to
  687. wrap iterators in procs of the same name which accumulate the result of the
  688. iterator and return it as a sequence, like ``split`` from the `strutils module
  689. <strutils.html>`_.
  690. Basic types
  691. ===========
  692. This section deals with the basic built-in types and the operations
  693. that are available for them in detail.
  694. Booleans
  695. --------
  696. Nim's boolean type is called ``bool`` and consists of the two
  697. pre-defined values ``true`` and ``false``. Conditions in while,
  698. if, elif, and when statements must be of type bool.
  699. The operators ``not, and, or, xor, <, <=, >, >=, !=, ==`` are defined
  700. for the bool type. The ``and`` and ``or`` operators perform short-circuit
  701. evaluation. For example:
  702. .. code-block:: nim
  703. while p != nil and p.name != "xyz":
  704. # p.name is not evaluated if p == nil
  705. p = p.next
  706. Characters
  707. ----------
  708. The `character type` is called ``char``. Its size is always one byte, so
  709. it cannot represent most UTF-8 characters, but it *can* represent one of the bytes
  710. that makes up a multi-byte UTF-8 character.
  711. The reason for this is efficiency: for the overwhelming majority of use-cases,
  712. the resulting programs will still handle UTF-8 properly as UTF-8 was especially
  713. designed for this.
  714. Character literals are enclosed in single quotes.
  715. Chars can be compared with the ``==``, ``<``, ``<=``, ``>``, ``>=`` operators.
  716. The ``$`` operator converts a ``char`` to a ``string``. Chars cannot be mixed
  717. with integers; to get the ordinal value of a ``char`` use the ``ord`` proc.
  718. Converting from an integer to a ``char`` is done with the ``chr`` proc.
  719. Strings
  720. -------
  721. String variables are **mutable**, so appending to a string
  722. is possible, and quite efficient. Strings in Nim are both zero-terminated and have a
  723. length field. A string's length can be retrieved with the builtin ``len``
  724. procedure; the length never counts the terminating zero. Accessing the
  725. terminating zero is an error, it only exists so that a Nim string can be converted
  726. to a ``cstring`` without doing a copy.
  727. The assignment operator for strings copies the string. You can use the ``&``
  728. operator to concatenate strings and ``add`` to append to a string.
  729. Strings are compared using their lexicographical order. All the comparison operators
  730. are supported. By convention, all strings are UTF-8 encoded, but this is not
  731. enforced. For example, when reading strings from binary files, they are merely
  732. a sequence of bytes. The index operation ``s[i]`` means the i-th *char* of
  733. ``s``, not the i-th *unichar*.
  734. A string variable is initialized with the empty string ``""``.
  735. Integers
  736. --------
  737. Nim has these integer types built-in:
  738. ``int int8 int16 int32 int64 uint uint8 uint16 uint32 uint64``.
  739. The default integer type is ``int``. Integer literals can have a *type suffix*
  740. to specify a non-default integer type:
  741. .. code-block:: nim
  742. :test: "nim c $1"
  743. let
  744. x = 0 # x is of type ``int``
  745. y = 0'i8 # y is of type ``int8``
  746. z = 0'i64 # z is of type ``int64``
  747. u = 0'u # u is of type ``uint``
  748. Most often integers are used for counting objects that reside in memory, so
  749. ``int`` has the same size as a pointer.
  750. The common operators ``+ - * div mod < <= == != > >=`` are defined for
  751. integers. The ``and or xor not`` operators are also defined for integers and
  752. provide *bitwise* operations. Left bit shifting is done with the ``shl``, right
  753. shifting with the ``shr`` operator. Bit shifting operators always treat their
  754. arguments as *unsigned*. For `arithmetic bit shifts`:idx: ordinary
  755. multiplication or division can be used.
  756. Unsigned operations all wrap around; they cannot lead to over- or under-flow
  757. errors.
  758. Lossless `Automatic type conversion`:idx: is performed in expressions where different
  759. kinds of integer types are used. However, if the type conversion
  760. would cause loss of information, the `EOutOfRange`:idx: exception is raised (if the error
  761. cannot be detected at compile time).
  762. Floats
  763. ------
  764. Nim has these floating-point types built-in: ``float float32 float64``.
  765. The default float type is ``float``. In the current implementation,
  766. ``float`` is always 64-bits.
  767. Float literals can have a *type suffix* to specify a non-default float
  768. type:
  769. .. code-block:: nim
  770. :test: "nim c $1"
  771. var
  772. x = 0.0 # x is of type ``float``
  773. y = 0.0'f32 # y is of type ``float32``
  774. z = 0.0'f64 # z is of type ``float64``
  775. The common operators ``+ - * / < <= == != > >=`` are defined for
  776. floats and follow the IEEE-754 standard.
  777. Automatic type conversion in expressions with different kinds of floating-point types is performed: the smaller type is converted to the larger. Integer
  778. types are **not** converted to floating-point types automatically, nor vice
  779. versa. Use the `toInt <system.html#toInt,float>`_ and
  780. `toFloat <system.html#toFloat,int>`_ procs for these conversions.
  781. Type Conversion
  782. ---------------
  783. Conversion between numerical types is performed by using the
  784. type as a function:
  785. .. code-block:: nim
  786. :test: "nim c $1"
  787. var
  788. x: int32 = 1.int32 # same as calling int32(1)
  789. y: int8 = int8('a') # 'a' == 97'i8
  790. z: float = 2.5 # int(2.5) rounds down to 2
  791. sum: int = int(x) + int(y) + int(z) # sum == 100
  792. Internal type representation
  793. ============================
  794. As mentioned earlier, the built-in `$ <dollars.html>`_ (stringify) operator
  795. turns any basic type into a string, which you can then print to the console
  796. using the ``echo`` proc. However, advanced types, and your own custom types,
  797. won't work with the ``$`` operator until you define it for them.
  798. Sometimes you just want to debug the current value of a complex type without
  799. having to write its ``$`` operator. You can use then the `repr
  800. <system.html#repr,T>`_ proc which works with any type and even complex data
  801. graphs with cycles. The following example shows that even for basic types
  802. there is a difference between the ``$`` and ``repr`` outputs:
  803. .. code-block:: nim
  804. :test: "nim c $1"
  805. var
  806. myBool = true
  807. myCharacter = 'n'
  808. myString = "nim"
  809. myInteger = 42
  810. myFloat = 3.14
  811. echo myBool, ":", repr(myBool)
  812. # --> true:true
  813. echo myCharacter, ":", repr(myCharacter)
  814. # --> n:'n'
  815. echo myString, ":", repr(myString)
  816. # --> nim:0x10fa8c050"nim"
  817. echo myInteger, ":", repr(myInteger)
  818. # --> 42:42
  819. echo myFloat, ":", repr(myFloat)
  820. # --> 3.1400000000000001e+00:3.1400000000000001e+00
  821. Advanced types
  822. ==============
  823. In Nim new types can be defined within a ``type`` statement:
  824. .. code-block:: nim
  825. :test: "nim c $1"
  826. type
  827. biggestInt = int64 # biggest integer type that is available
  828. biggestFloat = float64 # biggest float type that is available
  829. Enumeration and object types may only be defined within a
  830. ``type`` statement.
  831. Enumerations
  832. ------------
  833. A variable of an enumeration type can only be assigned one of the enumeration's specified values.
  834. These values are a set of ordered symbols. Each symbol is mapped
  835. to an integer value internally. The first symbol is represented
  836. at runtime by 0, the second by 1, and so on. For example:
  837. .. code-block:: nim
  838. :test: "nim c $1"
  839. type
  840. Direction = enum
  841. north, east, south, west
  842. var x = south # `x` is of type `Direction`; its value is `south`
  843. echo x # writes "south" to `stdout`
  844. All the comparison operators can be used with enumeration types.
  845. An enumeration's symbol can be qualified to avoid ambiguities:
  846. ``Direction.south``.
  847. The ``$`` operator can convert any enumeration value to its name, and the ``ord``
  848. proc can convert it to its underlying integer value.
  849. For better interfacing to other programming languages, the symbols of enum
  850. types can be assigned an explicit ordinal value. However, the ordinal values
  851. must be in ascending order.
  852. Ordinal types
  853. -------------
  854. Enumerations, integer types, ``char`` and ``bool`` (and
  855. subranges) are called ordinal types. Ordinal types have quite
  856. a few special operations:
  857. ----------------- --------------------------------------------------------
  858. Operation Comment
  859. ----------------- --------------------------------------------------------
  860. ``ord(x)`` returns the integer value that is used to
  861. represent `x`'s value
  862. ``inc(x)`` increments `x` by one
  863. ``inc(x, n)`` increments `x` by `n`; `n` is an integer
  864. ``dec(x)`` decrements `x` by one
  865. ``dec(x, n)`` decrements `x` by `n`; `n` is an integer
  866. ``succ(x)`` returns the successor of `x`
  867. ``succ(x, n)`` returns the `n`'th successor of `x`
  868. ``pred(x)`` returns the predecessor of `x`
  869. ``pred(x, n)`` returns the `n`'th predecessor of `x`
  870. ----------------- --------------------------------------------------------
  871. The `inc <system.html#inc,T,int>`_, `dec <system.html#dec,T,int>`_, `succ
  872. <system.html#succ,T,int>`_ and `pred <system.html#pred,T,int>`_ operations can
  873. fail by raising an `EOutOfRange` or `EOverflow` exception. (If the code has been
  874. compiled with the proper runtime checks turned on.)
  875. Subranges
  876. ---------
  877. A subrange type is a range of values from an integer or enumeration type
  878. (the base type). Example:
  879. .. code-block:: nim
  880. :test: "nim c $1"
  881. type
  882. MySubrange = range[0..5]
  883. ``MySubrange`` is a subrange of ``int`` which can only hold the values 0
  884. to 5. Assigning any other value to a variable of type ``MySubrange`` is a
  885. compile-time or runtime error. Assignments from the base type to one of its
  886. subrange types (and vice versa) are allowed.
  887. The ``system`` module defines the important `Natural <system.html#Natural>`_
  888. type as ``range[0..high(int)]`` (`high <system.html#high,typedesc[T]>`_ returns
  889. the maximal value). Other programming languages may suggest the use of unsigned
  890. integers for natural numbers. This is often **unwise**: you don't want unsigned
  891. arithmetic (which wraps around) just because the numbers cannot be negative.
  892. Nim's ``Natural`` type helps to avoid this common programming error.
  893. Sets
  894. ----
  895. .. include:: sets_fragment.txt
  896. Arrays
  897. ------
  898. An array is a simple fixed-length container. Each element in
  899. an array has the same type. The array's index type can be any ordinal type.
  900. Arrays can be constructed using ``[]``:
  901. .. code-block:: nim
  902. :test: "nim c $1"
  903. type
  904. IntArray = array[0..5, int] # an array that is indexed with 0..5
  905. var
  906. x: IntArray
  907. x = [1, 2, 3, 4, 5, 6]
  908. for i in low(x)..high(x):
  909. echo x[i]
  910. The notation ``x[i]`` is used to access the i-th element of ``x``.
  911. Array access is always bounds checked (at compile-time or at runtime). These
  912. checks can be disabled via pragmas or invoking the compiler with the
  913. ``--bound_checks:off`` command line switch.
  914. Arrays are value types, like any other Nim type. The assignment operator
  915. copies the whole array contents.
  916. The built-in `len <system.html#len,TOpenArray>`_ proc returns the array's
  917. length. `low(a) <system.html#low,openArray[T]>`_ returns the lowest valid index
  918. for the array `a` and `high(a) <system.html#high,openArray[T]>`_ the highest
  919. valid index.
  920. .. code-block:: nim
  921. :test: "nim c $1"
  922. type
  923. Direction = enum
  924. north, east, south, west
  925. BlinkLights = enum
  926. off, on, slowBlink, mediumBlink, fastBlink
  927. LevelSetting = array[north..west, BlinkLights]
  928. var
  929. level: LevelSetting
  930. level[north] = on
  931. level[south] = slowBlink
  932. level[east] = fastBlink
  933. echo repr(level) # --> [on, fastBlink, slowBlink, off]
  934. echo low(level) # --> north
  935. echo len(level) # --> 4
  936. echo high(level) # --> west
  937. The syntax for nested arrays (multidimensional) in other languages is a matter
  938. of appending more brackets because usually each dimension is restricted to the
  939. same index type as the others. In Nim you can have different dimensions with
  940. different index types, so the nesting syntax is slightly different. Building on
  941. the previous example where a level is defined as an array of enums indexed by
  942. yet another enum, we can add the following lines to add a light tower type
  943. subdivided into height levels accessed through their integer index:
  944. .. code-block:: nim
  945. type
  946. LightTower = array[1..10, LevelSetting]
  947. var
  948. tower: LightTower
  949. tower[1][north] = slowBlink
  950. tower[1][east] = mediumBlink
  951. echo len(tower) # --> 10
  952. echo len(tower[1]) # --> 4
  953. echo repr(tower) # --> [[slowBlink, mediumBlink, ...more output..
  954. # The following lines don't compile due to type mismatch errors
  955. #tower[north][east] = on
  956. #tower[0][1] = on
  957. Note how the built-in ``len`` proc returns only the array's first dimension
  958. length. Another way of defining the ``LightTower`` to better illustrate its
  959. nested nature would be to omit the previous definition of the ``LevelSetting``
  960. type and instead write it embedded directly as the type of the first dimension:
  961. .. code-block:: nim
  962. type
  963. LightTower = array[1..10, array[north..west, BlinkLights]]
  964. It is quite common to have arrays start at zero, so there's a shortcut syntax
  965. to specify a range from zero to the specified index minus one:
  966. .. code-block:: nim
  967. :test: "nim c $1"
  968. type
  969. IntArray = array[0..5, int] # an array that is indexed with 0..5
  970. QuickArray = array[6, int] # an array that is indexed with 0..5
  971. var
  972. x: IntArray
  973. y: QuickArray
  974. x = [1, 2, 3, 4, 5, 6]
  975. y = x
  976. for i in low(x)..high(x):
  977. echo x[i], y[i]
  978. Sequences
  979. ---------
  980. Sequences are similar to arrays but of dynamic length which may change
  981. during runtime (like strings). Since sequences are resizable they are always
  982. allocated on the heap and garbage collected.
  983. Sequences are always indexed with an ``int`` starting at position 0. The `len
  984. <system.html#len,seq[T]>`_, `low <system.html#low,openArray[T]>`_ and `high
  985. <system.html#high,openArray[T]>`_ operations are available for sequences too.
  986. The notation ``x[i]`` can be used to access the i-th element of ``x``.
  987. Sequences can be constructed by the array constructor ``[]`` in conjunction
  988. with the array to sequence operator ``@``. Another way to allocate space for
  989. a sequence is to call the built-in `newSeq <system.html#newSeq>`_ procedure.
  990. A sequence may be passed to an openarray parameter.
  991. Example:
  992. .. code-block:: nim
  993. :test: "nim c $1"
  994. var
  995. x: seq[int] # a reference to a sequence of integers
  996. x = @[1, 2, 3, 4, 5, 6] # the @ turns the array into a sequence allocated on the heap
  997. Sequence variables are initialized with ``@[]``.
  998. The ``for`` statement can be used with one or two variables when used with a
  999. sequence. When you use the one variable form, the variable will hold the value
  1000. provided by the sequence. The ``for`` statement is looping over the results
  1001. from the `items() <system.html#items.i,seq[T]>`_ iterator from the `system
  1002. <system.html>`_ module. But if you use the two-variable form, the first
  1003. variable will hold the index position and the second variable will hold the
  1004. value. Here the ``for`` statement is looping over the results from the
  1005. `pairs() <system.html#pairs.i,seq[T]>`_ iterator from the `system
  1006. <system.html>`_ module. Examples:
  1007. .. code-block:: nim
  1008. :test: "nim c $1"
  1009. for value in @[3, 4, 5]:
  1010. echo value
  1011. # --> 3
  1012. # --> 4
  1013. # --> 5
  1014. for i, value in @[3, 4, 5]:
  1015. echo "index: ", $i, ", value:", $value
  1016. # --> index: 0, value:3
  1017. # --> index: 1, value:4
  1018. # --> index: 2, value:5
  1019. Open arrays
  1020. -----------
  1021. **Note**: Openarrays can only be used for parameters.
  1022. Often fixed-size arrays turn out to be too inflexible; procedures should be
  1023. able to deal with arrays of different sizes. The `openarray`:idx: type allows
  1024. this. Openarrays are always indexed with an ``int`` starting at position 0.
  1025. The `len <system.html#len,TOpenArray>`_, `low <system.html#low,openArray[T]>`_
  1026. and `high <system.html#high,openArray[T]>`_ operations are available for open
  1027. arrays too. Any array with a compatible base type can be passed to an
  1028. openarray parameter, the index type does not matter.
  1029. .. code-block:: nim
  1030. :test: "nim c $1"
  1031. var
  1032. fruits: seq[string] # reference to a sequence of strings that is initialized with '@[]'
  1033. capitals: array[3, string] # array of strings with a fixed size
  1034. capitals = ["New York", "London", "Berlin"] # array 'capitals' allows assignment of only three elements
  1035. fruits.add("Banana") # sequence 'fruits' is dynamically expandable during runtime
  1036. fruits.add("Mango")
  1037. proc openArraySize(oa: openArray[string]): int =
  1038. oa.len
  1039. assert openArraySize(fruits) == 2 # procedure accepts a sequence as parameter
  1040. assert openArraySize(capitals) == 3 # but also an array type
  1041. The openarray type cannot be nested: multidimensional openarrays are not
  1042. supported because this is seldom needed and cannot be done efficiently.
  1043. Varargs
  1044. -------
  1045. A ``varargs`` parameter is like an openarray parameter. However, it is
  1046. also a means to implement passing a variable number of
  1047. arguments to a procedure. The compiler converts the list of arguments
  1048. to an array automatically:
  1049. .. code-block:: nim
  1050. :test: "nim c $1"
  1051. proc myWriteln(f: File, a: varargs[string]) =
  1052. for s in items(a):
  1053. write(f, s)
  1054. write(f, "\n")
  1055. myWriteln(stdout, "abc", "def", "xyz")
  1056. # is transformed by the compiler to:
  1057. myWriteln(stdout, ["abc", "def", "xyz"])
  1058. This transformation is only done if the varargs parameter is the
  1059. last parameter in the procedure header. It is also possible to perform
  1060. type conversions in this context:
  1061. .. code-block:: nim
  1062. :test: "nim c $1"
  1063. proc myWriteln(f: File, a: varargs[string, `$`]) =
  1064. for s in items(a):
  1065. write(f, s)
  1066. write(f, "\n")
  1067. myWriteln(stdout, 123, "abc", 4.0)
  1068. # is transformed by the compiler to:
  1069. myWriteln(stdout, [$123, $"abc", $4.0])
  1070. In this example `$ <dollars.html>`_ is applied to any argument that is passed
  1071. to the parameter ``a``. Note that `$ <dollars.html>`_ applied to strings is a
  1072. nop.
  1073. Slices
  1074. ------
  1075. Slices look similar to subranges types in syntax but are used in a different
  1076. context. A slice is just an object of type Slice which contains two bounds,
  1077. `a` and `b`. By itself a slice is not very useful, but other collection types
  1078. define operators which accept Slice objects to define ranges.
  1079. .. code-block:: nim
  1080. :test: "nim c $1"
  1081. var
  1082. a = "Nim is a programming language"
  1083. b = "Slices are useless."
  1084. echo a[7 .. 12] # --> 'a prog'
  1085. b[11 .. ^2] = "useful"
  1086. echo b # --> 'Slices are useful.'
  1087. In the previous example slices are used to modify a part of a string. The
  1088. slice's bounds can hold any value supported by
  1089. their type, but it is the proc using the slice object which defines what values
  1090. are accepted.
  1091. To understand some of the different ways of specifying the indices of
  1092. strings, arrays, sequences, etc., it must be remembered that Nim uses
  1093. zero-based indices.
  1094. So the string ``b`` is of length 19, and two different ways of specifying the
  1095. indices are
  1096. .. code-block:: nim
  1097. "Slices are useless."
  1098. | | |
  1099. 0 11 17 using indices
  1100. ^19 ^8 ^2 using ^ syntax
  1101. where ``b[0 .. ^1]`` is equivalent to ``b[0 .. b.len-1]`` and ``b[0 ..< b.len]``, and it
  1102. can be seen that the ``^1`` provides a short-hand way of specifying the ``b.len-1``. See
  1103. the `backwards index operator <system.html#^.t%2Cint>`_.
  1104. In the above example, because the string ends in a period, to get the portion of the
  1105. string that is "useless" and replace it with "useful".
  1106. ``b[11 .. ^2]`` is the portion "useless", and ``b[11 .. ^2] = "useful"`` replaces the
  1107. "useless" portion with "useful", giving the result "Slices are useful."
  1108. Note 1: alternate ways of writing this are ``b[^8 .. ^2] = "useful"`` or
  1109. as ``b[11 .. b.len-2] = "useful"`` or as ``b[11 ..< b.len-1] = "useful"``.
  1110. Note 2: As the ``^`` template returns a `distinct int <manual.html#types-distinct-type>`_
  1111. of type ``BackwardsIndex``, we can have a ``lastIndex`` constant defined as ``const lastIndex = ^1``,
  1112. and later used as ``b[0 .. lastIndex]``.
  1113. Objects
  1114. -------
  1115. The default type to pack different values together in a single
  1116. structure with a name is the object type. An object is a value type,
  1117. which means that when an object is assigned to a new variable all its
  1118. components are copied as well.
  1119. Each object type ``Foo`` has a constructor ``Foo(field: value, ...)``
  1120. where all of its fields can be initialized. Unspecified fields will
  1121. get their default value.
  1122. .. code-block:: nim
  1123. type
  1124. Person = object
  1125. name: string
  1126. age: int
  1127. var person1 = Person(name: "Peter", age: 30)
  1128. echo person1.name # "Peter"
  1129. echo person1.age # 30
  1130. var person2 = person1 # copy of person 1
  1131. person2.age += 14
  1132. echo person1.age # 30
  1133. echo person2.age # 44
  1134. # the order may be changed
  1135. let person3 = Person(age: 12, name: "Quentin")
  1136. # not every member needs to be specified
  1137. let person4 = Person(age: 3)
  1138. # unspecified members will be initialized with their default
  1139. # values. In this case it is the empty string.
  1140. doAssert person4.name == ""
  1141. Object fields that should be visible from outside the defining module have to
  1142. be marked with ``*``.
  1143. .. code-block:: nim
  1144. :test: "nim c $1"
  1145. type
  1146. Person* = object # the type is visible from other modules
  1147. name*: string # the field of this type is visible from other modules
  1148. age*: int
  1149. Tuples
  1150. ------
  1151. Tuples are very much like what you have seen so far from objects. They
  1152. are value types where the assignment operator copies each component.
  1153. Unlike object types though, tuple types are structurally typed,
  1154. meaning different tuple-types are *equivalent* if they specify fields of
  1155. the same type and of the same name in the same order.
  1156. The constructor ``()`` can be used to construct tuples. The order of the
  1157. fields in the constructor must match the order in the tuple's
  1158. definition. But unlike objects, a name for the tuple type may not be
  1159. used here.
  1160. Like the object type the notation ``t.field`` is used to access a
  1161. tuple's field. Another notation that is not available for objects is
  1162. ``t[i]`` to access the ``i``'th field. Here ``i`` must be a constant
  1163. integer.
  1164. .. code-block:: nim
  1165. :test: "nim c $1"
  1166. type
  1167. # type representing a person:
  1168. # A person consists of a name and an age.
  1169. Person = tuple
  1170. name: string
  1171. age: int
  1172. # Alternative syntax for an equivalent type.
  1173. PersonX = tuple[name: string, age: int]
  1174. # anonymous field syntax
  1175. PersonY = (string, int)
  1176. var
  1177. person: Person
  1178. personX: PersonX
  1179. personY: PersonY
  1180. person = (name: "Peter", age: 30)
  1181. # Person and PersonX are equivalent
  1182. personX = person
  1183. # Create a tuple with anonymous fields:
  1184. personY = ("Peter", 30)
  1185. # A tuple with anonymous fields is compatible with a tuple that has
  1186. # field names.
  1187. person = personY
  1188. personY = person
  1189. # Usually used for short tuple initialization syntax
  1190. person = ("Peter", 30)
  1191. echo person.name # "Peter"
  1192. echo person.age # 30
  1193. echo person[0] # "Peter"
  1194. echo person[1] # 30
  1195. # You don't need to declare tuples in a separate type section.
  1196. var building: tuple[street: string, number: int]
  1197. building = ("Rue del Percebe", 13)
  1198. echo building.street
  1199. # The following line does not compile, they are different tuples!
  1200. #person = building
  1201. # --> Error: type mismatch: got (tuple[street: string, number: int])
  1202. # but expected 'Person'
  1203. Even though you don't need to declare a type for a tuple to use it, tuples
  1204. created with different field names will be considered different objects despite
  1205. having the same field types.
  1206. Tuples can be *unpacked* during variable assignment (and only then!). This can
  1207. be handy to assign directly the fields of the tuples to individually named
  1208. variables. An example of this is the `splitFile <os.html#splitFile,string>`_
  1209. proc from the `os module <os.html>`_ which returns the directory, name, and
  1210. extension of a path at the same time. For tuple unpacking to work you must
  1211. use parentheses around the values you want to assign the unpacking to,
  1212. otherwise, you will be assigning the same value to all the individual
  1213. variables! For example:
  1214. .. code-block:: nim
  1215. :test: "nim c $1"
  1216. import os
  1217. let
  1218. path = "usr/local/nimc.html"
  1219. (dir, name, ext) = splitFile(path)
  1220. baddir, badname, badext = splitFile(path)
  1221. echo dir # outputs `usr/local`
  1222. echo name # outputs `nimc`
  1223. echo ext # outputs `.html`
  1224. # All the following output the same line:
  1225. # `(dir: usr/local, name: nimc, ext: .html)`
  1226. echo baddir
  1227. echo badname
  1228. echo badext
  1229. Fields of tuples are always public, they don't need to be explicity
  1230. marked to be exported, unlike for example fields in an object type.
  1231. Reference and pointer types
  1232. ---------------------------
  1233. References (similar to pointers in other programming languages) are a
  1234. way to introduce many-to-one relationships. This means different references can
  1235. point to and modify the same location in memory.
  1236. Nim distinguishes between `traced`:idx: and `untraced`:idx: references.
  1237. Untraced references are also called *pointers*. Traced references point to
  1238. objects in a garbage-collected heap, untraced references point to
  1239. manually allocated objects or objects elsewhere in memory. Thus
  1240. untraced references are *unsafe*. However, for certain low-level operations
  1241. (e.g., accessing the hardware), untraced references are necessary.
  1242. Traced references are declared with the **ref** keyword; untraced references
  1243. are declared with the **ptr** keyword.
  1244. The empty ``[]`` subscript notation can be used to *de-refer* a reference,
  1245. meaning to retrieve the item the reference points to. The ``.`` (access a
  1246. tuple/object field operator) and ``[]`` (array/string/sequence index operator)
  1247. operators perform implicit dereferencing operations for reference types:
  1248. .. code-block:: nim
  1249. :test: "nim c $1"
  1250. type
  1251. Node = ref object
  1252. le, ri: Node
  1253. data: int
  1254. var
  1255. n: Node
  1256. new(n)
  1257. n.data = 9
  1258. # no need to write n[].data; in fact n[].data is highly discouraged!
  1259. To allocate a new traced object, the built-in procedure ``new`` must be used.
  1260. To deal with untraced memory, the procedures ``alloc``, ``dealloc`` and
  1261. ``realloc`` can be used. The `system <system.html>`_
  1262. module's documentation contains further details.
  1263. If a reference points to *nothing*, it has the value ``nil``.
  1264. Procedural type
  1265. ---------------
  1266. A procedural type is a (somewhat abstract) pointer to a procedure.
  1267. ``nil`` is an allowed value for a variable of a procedural type.
  1268. Nim uses procedural types to achieve `functional`:idx: programming
  1269. techniques.
  1270. Example:
  1271. .. code-block:: nim
  1272. :test: "nim c $1"
  1273. proc echoItem(x: int) = echo x
  1274. proc forEach(action: proc (x: int)) =
  1275. const
  1276. data = [2, 3, 5, 7, 11]
  1277. for d in items(data):
  1278. action(d)
  1279. forEach(echoItem)
  1280. A subtle issue with procedural types is that the calling convention of the
  1281. procedure influences the type compatibility: procedural types are only compatible
  1282. if they have the same calling convention. The different calling conventions are
  1283. listed in the `manual <manual.html#types-procedural-type>`_.
  1284. Distinct type
  1285. -------------
  1286. A Distinct type allows for the creation of a new type that "does not imply a
  1287. subtype relationship between it and its base type".
  1288. You must **explicitly** define all behavior for the distinct type.
  1289. To help with this, both the distinct type and its base type can cast from one
  1290. type to the other.
  1291. Examples are provided in the `manual <manual.html#types-distinct-type>`_.
  1292. Modules
  1293. =======
  1294. Nim supports splitting a program into pieces with a module concept.
  1295. Each module is in its own file. Modules enable `information hiding`:idx: and
  1296. `separate compilation`:idx:. A module may gain access to the symbols of another
  1297. module by using the `import`:idx: statement. Only top-level symbols that are marked
  1298. with an asterisk (``*``) are exported:
  1299. .. code-block:: nim
  1300. # Module A
  1301. var
  1302. x*, y: int
  1303. proc `*` *(a, b: seq[int]): seq[int] =
  1304. # allocate a new sequence:
  1305. newSeq(result, len(a))
  1306. # multiply two int sequences:
  1307. for i in 0..len(a)-1: result[i] = a[i] * b[i]
  1308. when isMainModule:
  1309. # test the new ``*`` operator for sequences:
  1310. assert(@[1, 2, 3] * @[1, 2, 3] == @[1, 4, 9])
  1311. The above module exports ``x`` and ``*``, but not ``y``.
  1312. A module's top-level statements are executed at the start of the program.
  1313. This can be used to initialize complex data structures for example.
  1314. Each module has a special magic constant ``isMainModule`` that is true if the
  1315. module is compiled as the main file. This is very useful to embed tests within
  1316. the module as shown by the above example.
  1317. A symbol of a module *can* be *qualified* with the ``module.symbol`` syntax. And if
  1318. a symbol is ambiguous, it *must* be qualified. A symbol is ambiguous
  1319. if it is defined in two (or more) different modules and both modules are
  1320. imported by a third one:
  1321. .. code-block:: nim
  1322. # Module A
  1323. var x*: string
  1324. .. code-block:: nim
  1325. # Module B
  1326. var x*: int
  1327. .. code-block:: nim
  1328. # Module C
  1329. import A, B
  1330. write(stdout, x) # error: x is ambiguous
  1331. write(stdout, A.x) # okay: qualifier used
  1332. var x = 4
  1333. write(stdout, x) # not ambiguous: uses the module C's x
  1334. But this rule does not apply to procedures or iterators. Here the overloading
  1335. rules apply:
  1336. .. code-block:: nim
  1337. # Module A
  1338. proc x*(a: int): string = $a
  1339. .. code-block:: nim
  1340. # Module B
  1341. proc x*(a: string): string = $a
  1342. .. code-block:: nim
  1343. # Module C
  1344. import A, B
  1345. write(stdout, x(3)) # no error: A.x is called
  1346. write(stdout, x("")) # no error: B.x is called
  1347. proc x*(a: int): string = discard
  1348. write(stdout, x(3)) # ambiguous: which `x` is to call?
  1349. Excluding symbols
  1350. -----------------
  1351. The normal ``import`` statement will bring in all exported symbols.
  1352. These can be limited by naming symbols that should be excluded using
  1353. the ``except`` qualifier.
  1354. .. code-block:: nim
  1355. import mymodule except y
  1356. From statement
  1357. --------------
  1358. We have already seen the simple ``import`` statement that just imports all
  1359. exported symbols. An alternative that only imports listed symbols is the
  1360. ``from import`` statement:
  1361. .. code-block:: nim
  1362. from mymodule import x, y, z
  1363. The ``from`` statement can also force namespace qualification on
  1364. symbols, thereby making symbols available, but needing to be qualified
  1365. in order to be used.
  1366. .. code-block:: nim
  1367. from mymodule import x, y, z
  1368. x() # use x without any qualification
  1369. .. code-block:: nim
  1370. from mymodule import nil
  1371. mymodule.x() # must qualify x with the module name as prefix
  1372. x() # using x here without qualification is a compile error
  1373. Since module names are generally long to be descriptive, you can also
  1374. define a shorter alias to use when qualifying symbols.
  1375. .. code-block:: nim
  1376. from mymodule as m import nil
  1377. m.x() # m is aliasing mymodule
  1378. Include statement
  1379. -----------------
  1380. The ``include`` statement does something fundamentally different than
  1381. importing a module: it merely includes the contents of a file. The ``include``
  1382. statement is useful to split up a large module into several files:
  1383. .. code-block:: nim
  1384. include fileA, fileB, fileC
  1385. Part 2
  1386. ======
  1387. So, now that we are done with the basics, let's see what Nim offers apart
  1388. from a nice syntax for procedural programming: `Part II <tut2.html>`_
  1389. .. _strutils: strutils.html
  1390. .. _system: system.html