tut1.rst 58 KB

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