app_0b.md 20 KB

Appendix B: Nim standard library cheat sheet

                                 289

B.1. Integers Integer functionality is available via the automatically imported system module. Table 11. Operations on integers Operation Example div: Integer division (without 13 div 5 == 2 a remainder). mod: Integer modulo 13 mod 5 == 3 (remainder). shl: Shift left. 1 shl 3 == 8 shr: Shift right. 8 shr 1 == 4 and: Bitwise and. 0b0011 and 0b0101 == 0b0001 or: Bitwise or. 0b0011 or 0b0101 == 0b0111 xor: Bitwise xor. 0b0011 xor 0b0101 == 0b0110 toInt: Converts a floating toInt(2.49) == 2 point number into an integer. toInt(2.5) == 3 inc: Increments the value of var x = 5 an ordinal variable. inc x

                              assert x == 6
                              inc x, 3
                              assert x == 9

dec: Decrements the value of var x = 5 an ordinal variable. dec x

                              assert x == 4
                              dec x, 3
                              assert x == 1

290 B.2. Strings To use some of the available functionality on strings, you need to import std/strutils. Table 12. String-related functionality Operation Example $: Converts a type into a $123 == "123" string. add: Add a character to a "abc".add 'd' == "abcd" string. &: Concatenation of two "ab" & "cd" == "abcd" strings. join: Concatenation with a ["ab", "cd", "ef"].join("-x-") == "ab-x-cd- string between each element. x-ef" split: Splits a string on split("ab cd") == @["ab", "cd"] whitespace characters. split: Splits a string on a "abxcd".split('x') == @["ab", "cd"] given character. find: Searches for a character "abcd".find('c') == 2 inside of a string. find: Searches for a substring "abcd".find("bc") == 1 inside of a string. replace: Replaces every "acdc".replace('c', 'x') == "axdx" occurrence of a given character with a new one.

                                                                        291

B.3. Sequences To use some of the available functionality on sequences, you need to import std/sequtils. Table 13. Seq-related functionality Operation Example toSeq: Converts an iterable toSeq(1..3) == @[1, 2, 3] into a sequence. @: Converts arrays and strings @"abc" == @['a', 'b', 'c'] to a sequence. &: Concatenation of two @[1, 2] & @[3, 4] == @[1, 2, 3, 4] sequences. map: Applies a proc to every proc double(x: int): int = item in a sequence. 2*x

                               var a = @[1, 3, 5]
                               var b = a.map(double)
                               assert b == @[2, 6, 10]

filter: Returns a new proc small(x: int): bool = sequence with values that x < 4 satisfy a predicate. var a = @[1, 3, 5]

                               var b = a.filter(small)
                               assert b == @[1, 3]

292 B.4. Bit sets Bit sets are built-in, i.e. available via the automatically imported system module. Table 14. Bit sets operations Operation Example incl: Include an element in var a = {5 .. 8} the set. a.incl 3

                              assert a == {3, 5, 6, 7, 8}

excl: Exclude an element var a = {5 .. 8} from the set. a.excl 5

                              assert a == {6, 7, 8}

*: Intersection between two assert {1, 2} * {2, 3} == {2} sets. +: Union between two sets. assert {1, 2} * {2, 3} == {1, 2, 3} -: Difference between two assert {1, 2} - {2, 3} == {1} sets. <: A proper subset. assert {1, 2} < {1, 2, 3}

                              assert not({1, 2} < {1, 2})
                                                                   293

B.5. Hashes To implement hashing for custom types, one can import the std/hashes module. Table 15. Hashing operations Operation Example !&: Mixing a hash value. var h: Hash = 0

                            for element in mySeq:
                              h = h !& hash(element)

!$: Finishing the hash value. var h: Hash = 0

                            for element in mySeq:
                              h = h !& hash(element)
                            h = !$h

294 B.6. Hash sets Hash sets are available with import std/sets. Table 16. Hash sets operations Operation Example toHashSet: Converts a assert toHashSet("acdc") == ['a', 'c', collection to a hash set. 'd'].toHashSet *, intersection: Intersection var a = [1, 2].toHashSet between two sets. var b = [2, 3].toHashSet

                             assert a * b == [2].toHashSet

+, union: Union between two var a = [1, 2].toHashSet sets. var b = [2, 3].toHashSet

                             assert a + b == [1, 2, 3].toHashSet

-, difference: Difference var a = [1, 2].toHashSet between two sets. var b = [2, 3].toHashSet

                             assert a - b == [1].toHashSet
                             assert b - a == [3].toHashSet

<: A proper subset. var a = [1, 2].toHashSet

                             var c = [1, 2, 3].toHashSet
                             assert a < c
                             assert not(a < a)

<=: A subset. var a = [1, 2].toHashSet

                             var c = [1, 2, 3].toHashSet
                             assert a <= c
                             assert a <= a

card, len: Number of assert card([1, 2].toHashSet) == 2 elements in a set. pop: Removes and returns a var s = [1, 2, 3].toHashSet random element from a set. let x = s.pop

                             assert card(s) == 2
                                                                    295

Operation Example containsOrIncl: Adds an var s = [1, 2].toHashSet element to the set, and assert s.containsOrIncl(1) returns true if the key assert not s.containsOrIncl(9)

                     assert s == [1, 2, 9].toHashSet

already existed. 296 B.7. Hash tables Hash tables are available with import std/tables. Table 17. Tables-related functionality Operation Example initTable: Initializes an var a = initTable[int, string]() empty hash table. toTable: Creates a table from var a = toTable([(5, "ab"), (7, "cd")]) a container of pairs. []=: Inserts a key-value pair var a = toTable([(5, "ab"), (7, "cd")]) into a table. a[9] = "ef" []: Retrieves a value from a var a = toTable([(5, "ab"), (7, "cd")]) given key. Raises an echo a[5] # => "ab" exception if a key doesn’t echo a[9] # => raises KeyError exist. getOrDefault: Retrieves a var a = toTable([(5, "ab"), (7, "cd")]) value from a given key. echo a.getOrDefault(5) # => "ab" Returns a default (or echo a.getOrDefault(9) # => ""

                              echo a.getOrDefault(5, "ef") # => "ab"

provided) value if a key

                              echo a.getOrDefault(9, "ef") # => "ef"

doesn’t exist. hasKey: Checks if a given key var a = toTable([(5, "ab"), (7, "cd")]) is in the table. assert a.hasKey(5)

                              assert not a.hasKey(9)

hasKeyOrPut: Returns true if a var a = toTable([(5, "ab"), (7, "cd")]) given key is in the table. if a.hasKeyOrPut(7, "ef"): Otherwise inserts a value. a[5].add 'z'

                              if a.hasKeyOrPut(9, "gh"):
                                 a[5].add 'y'
                              assert a == {5: "abz", 7: "cd", 9:
                              "gh"}.toTable

mgetOrPut: Gets a value of a var a = toTable([(5, "ab"), (7, "cd")]) given key, or puts a new a.mgetOrPut(5, "xy").add 'z' value if the key doesn’t exist. a.mgetOrPut(9, "ef").add 'y'

                              assert a == {5: "abz", 7: "cd", 9:

Returns a modifiable value.

                              "efy"}.toTable
                                                                      297

Operation Example del: Deletes a key from the var a = toTable([(5, "ab"), (7, "cd")]) table. Does nothing if the key a.del(5) is not in the table. a.del(9)

                            assert a == {7: "cd"}.toTable

pop: Deletes a key from the var a = toTable([(5, "ab"), (7, "cd")]) table. Returns true if the key var s = "" existed, and sets the given assert a.pop(5, s)

                            assert s == "ab"

variable to the value of the

                            s = ""

key. Returns false if the key

                            assert not a.pop(9, s)

didn’t exist, and the variable assert s == "" is unchanged. 298 B.8. Optionals Types which encapsulate optional value are available with import std/options. Table 18. Optionals-related functionality Operation Example Option[T]: Type of an var a: Option[int] optional variable. some: Returns a value of an var a: Option[int] Option. a = some(31) none: Returns an Option that var a: Option[int] has no value. a = none(int) isSome: Checks if an Option assert some(31).isSome contains a value. assert not none(int).isSome isNone: Checks if an Option is assert not some(31).isNone empty. assert none(int).isNone get: Return a value of an assert some(31).get(-1) == 31 Option or a default value if assert none(int).get(-1) == -1 there is no value. filter: Applies a function to proc isOdd(x: int): bool = the value of an Option. x mod 2 == 1

                               assert some(31).filter(isOdd) == some(31)
                               assert some(32).filter(isOdd) == none(int)
                               assert none(int).filter(isOdd) == none(int)

map: Applies a function to the proc isOdd(x: int): bool = value of an Option and x mod 2 == 1 returns a new Option.

                               assert some(31).map(isOdd) == some(true)
                               assert some(32).map(isOdd) == none(bool)
                               assert none(int).map(isOdd) == none(bool)
                                                                         299

B.9. String formatting String formatting and interpolation is available with import std/strformat. One can use either fmt or & for formatting. Note that the string in fmt"{expr}" is a generalized raw string literal, i.e. \n will not be interpreted as a newline (the \ will be escaped). The & will interpret \n as a new line: import std/strformat let msg = "hello" assert fmt"{msg}\n" == "hello\n" assert &"{msg}\n" == "hello\n" Table 19. String format functionality Operation Example <, ^, >: Left (default for let s = "nim" strings), center, right (default let x = 987.12 for numbers) alignment.

                                assert fmt"{s:5}" == "nim   "
                                assert fmt"{s:<5}" == "nim    "
                                assert fmt"{s:>5}" == "   nim"
                                assert fmt"{s:^5}" == " nim "
                                assert fmt"{x:8.2f}" == "   987.12"
                                assert fmt"{x:8.4f}" == "987.1200"
                                assert fmt"{x:<8.1f}" == "987.1     "

fmt"{expr=}": This expands to let s = "nim" fmt"expr={expr}", which is useful for debugging. assert fmt"{s=}" == "s=nim"

                                assert fmt"{s = }" == "s = nim"

300 B.10. Algorithms Some common algorithms on arrays and sequences are available via import std/algorithm. Table 20. Algorithm functionality Operation Example binarySearch: Assumes the var a = [50, 60, 70, 80] container is sorted and assert a.binarySearch(70) == 2 binary searches for an element. fill: Fills a slice of a var a: array[5, int] container with a value. If no a.fill(2, 4, 99) range is specified, it assigns a assert a == [0, 0, 99, 99, 99]

                               a.fill(88)

value to all elements.

                               assert a == [88, 88, 88, 88, 88]

reverse: Reverses a slice of a var a = [10, 20, 30, 40, 50, 60] container. If no range is a.reverse(1, 3) specified, it reverses the assert a == [10, 40, 30, 20, 50, 60]

                               a.reverse()

whole container.

                               assert a == [60, 50, 20, 30, 40, 10]

nextPermutation: Modifies a var a = [10, 20, 30, 40] container, changing it to the assert a.nextPermutation() == true next lexicographic assert a == [10, 20, 40, 30] permutation. Returns true if

                               a = [40, 30, 20, 10]

a permutation happened (the

                               assert a.nextPermutation() == false

last-ordered permutation was assert a == [40, 30, 20, 10] not reached). prevPermutation: Modifies a var a = [10, 20, 30, 40] container, changing it to the assert a.prevPermutation() == false previous lexicographic assert a == [10, 20, 30, 40] permutation. Returns true if

                               a = [40, 30, 10, 20]

a permutation happened (the

                               assert a.prevPermutation() == true

first-ordered permutation assert a == [40, 20, 30, 10] was not reached).

                                                                    301

Operation Example product: Cartesian product. var a = @[10, 20, 30]

                            var b = @[99, 88]
                            assert product([a, b]) == @[
                              @[30, 88], @[20, 88], @[10, 88],
                              @[30, 99], @[20, 99], @[10, 99],
                            ]

rotateLeft, rotatedLeft: Left var a = [10, 20, 30, 40, 50] rotation of a container. For a.rotateLeft(1) right rotation use negative assert a == [20, 30, 40, 50, 10] distance. rotateLeft is an in-

                            assert a.rotatedLeft(-2) == @[50, 10, 20,

place version of rotatedLeft.

                            30, 40]

sort, sorted: Merge sort of a var a = [20, 40, 50, 10, 30] container. sort is an in-place version of sorted. assert sorted(a) == @[10, 20, 30, 40, 50]

                            a.sort(Descending)
                            assert a == [50, 40, 30, 20, 10]

302 B.11. OS Basic operating system facilities are available with import std/os. Table 21. OS functionality Operation Example /, joinPath: Joins two "foo" / "bar" == "foo/bar" directory names to one. addFileExt: Adds an addFileExt("foo", "bar") == "foo.bar" extension to a filename addFileExt("foo.exe", "bar") == "foo.exe" without one. changeFileExt: Changes an changeFileExt("foo", "bar") == "foo.bar" extension of a filename. Pass changeFileExt("foo.exe", "bar") == "" to remove an existing "foo.bar"

                               changeFileExt("foo.exe", "") == "foo"

extension. execShellCmd: Executes a shell assert execShellCmd("ls -la") == 0 command and returns its error code. extractFilename: Extracts the extractFilename("foo/bar/baz.exe") == filename of a given path. "baz.exe"

                               extractFilename("foo/bar/") == ""

parentDir: Returns the parent parentDir("foo/bar/baz.exe") == "foo/bar" directory of a path. parentDir("foo/bar/") == "foo" splitFile: Splits a filename splitFile("foo/bar/baz.exe") == ("foo/bar", into a tuple containing "baz", ".exe") directory, filename, and splitFile("foo/bar/") == ("foo/bar", "",

                               "")

extension.

                                                                         303

Operation Example paramCount: Returns the myfile.nim number of command line

                      import os

arguments given to the application. echo paramCount()

                      > ./myfile
                      0
                      > ./myfile foo bar
                      2

paramStr: Returns n-th myfile.nim command line argument

                      import os

given to the application

                      echo paramStr(1)
                      > ./myfile foo bar
                      foo

304 B.12. JSON Basic JSON support is available via import std/json. Table 22. JSON functionality Operation Example parseJson: Creates a JSON tree let jsonNode = parseJson("""{"key": from a string. 3.14}""")

                              assert jsonNode.kind == JObject
                              assert jsonNode["key"].kind == JFloat

pretty: Produces a pretty let a = parseJson("""{"key": 3.14}""") string representation for the echo pretty(a) provided JSON tree. getInt: Retrieves the int var a = %60 value of a JInt JsonNode. assert a.getInt == 60 getFloat: Retrieves the float var a = %60.0 value of a JFloat JsonNode. assert a.getFloat == 60.0 getStr: Retrieves the string var a = %"abc" value of a JString JsonNode. assert a.getStr == "abc" getBool: Retrieves the bool var a = %true value of a JBool JsonNode. assert a.getBool == true %: Generic constructor for let s = %"abc" JSON data. Can construct let i = %5 atoms and composed arrays let f = %5.5

                              let b = %false

and objects.

                              let a = %[%5, %5.0, %"x", %true,
                                        %{"key": %8, "keyB": %9}]
                              assert $a ==
                                """[5,5.0,"x",true,{"key":8,"keyB":9}]"""

%: Generic constructor for let a = %[5, 5.0, "x", true, JSON data and does so {"key": 8, "keyB": 9}] recursively. Can construct

                              assert $a ==

atoms and composed arrays

                                """[5,5.0,"x",true,{"key":8,"keyB":9}]"""

and objects.

                                                                       305

B.13. Unicode Basic Unicode support is available via import std/unicode. A Unicode code point is called a Rune. Table 23. Unicode functionality Operation Example runeLen: Returns the number let a = "añyóng" of runes of a string. assert a.runeLen == 6

                             assert a.len == 8

runeAt: Returns the rune of let a = "añyóng" the given string at the given assert a.runeAt(1) == "ñ".runeAt(0) byte index. assert a.runeAt(2) == "ñ".runeAt(1)

                             assert a.runeAt(3) == "y".runeAt(0)

validateUtf8: Returns the assert validateUtf8("añyóng") == -1 position of the first invalid byte that does not hold valid UTF-8 data. If every byte is valid -1 is returned. runes: Iterates over any rune for r in runes("añyóng"): of a string. echo r == Rune('g') cmpRunesIgnoreCase: assert cmpRunesIgnoreCase("añyóng", Compares two UTF-8 strings "anyong") > 0 and ignores the case. Returns: 0 if a == b and a value < 0 if a < b and a value

0` if a > b. toUTF8, $: Converts a rune assert toUTF8("añyóng".runeAt(1)) == "ñ" into its UTF-8 representation. $ is an alias for toUTF8.