tut1.rst 57 KB

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