tut1.rst 58 KB

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