tut1.rst 58 KB

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