tut1.rst 58 KB

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