tut1.rst 58 KB

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