summary refs log tree commit diff stats
path: root/tests/niminaction/Chapter2/various2.nim
blob: 921f38c7d13751c4114be6fd325738d36d022a81 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
discard """
  exitCode: 0
  outputsub: '''42 is greater than 0'''
"""

if 42 >= 0:
  echo "42 is greater than 0"


echo("Output: ",
  5)
echo(5 +
  5)
# --- Removed code that is supposed to fail here. Not going to test those. ---

# Single-line comment
#[
Multiline comment
]#
when false:
  echo("Commented-out code")

let decimal = 42
let hex = 0x42
let octal = 0o42
let binary = 0b101010

let a: int16 = 42
let b = 42'i8

let c = 1'f32 # --- Changed names here to avoid clashes ---
let d = 1.0e19

let e = false
let f = true

let g = 'A'
let h = '\109'
let i = '\x79'

let text = "The book title is \"Nim in Action\""

let filepath = "C:\\Program Files\\Nim"

# --- Changed name here to avoid clashes ---
let filepath1 = r"C:\Program Files\Nim"

let multiLine = """foo
  bar
  baz
"""
echo multiLine

import strutils
# --- Changed name here to avoid clashes ---
let multiLine1 = """foo
  bar
  baz
"""
echo multiLine1.unindent
doAssert multiLine1.unindent == "foo\nbar\nbaz\n"

proc fillString(): string =
  result = ""
  echo("Generating string")
  for i in 0 .. 4:
    result.add($i) #<1>

const count = fillString()

var
  text1 = "hello"
  number: int = 10
  isTrue = false

var  = "Fire"
let ogień = true

var `var` = "Hello"
echo(`var`)

proc myProc(name: string): string = "Hello " & name
discard myProc("Dominik")

proc bar(): int #<1>

proc foo(): float = bar().float
proc bar(): int = foo().int

proc noReturn() = echo("Hello")
proc noReturn2(): void = echo("Hello")

proc noReturn3 = echo("Hello")

proc message(recipient: string): auto =
  "Hello " & recipient

doAssert message("Dom") == "Hello Dom"

proc max(a: int, b: int): int =
  if a > b: a else: b

doAssert max(5, 10) == 10

proc max2(a, b: int): int =
  if a > b: a else: b

proc genHello(name: string, surname = "Doe"): string =
  "Hello " & name & " " & surname

# -- Leaving these as asserts as that is in the original code, just in case
# -- somehow in the future `assert` is removed :)
assert genHello("Peter") == "Hello Peter Doe"
assert genHello("Peter", "Smith") == "Hello Peter Smith"

proc genHello2(names: varargs[string]): string =
  result = ""
  for name in names:
    result.add("Hello " & name & "\n")

doAssert genHello2("John", "Bob") == "Hello John\nHello Bob\n"

proc getUserCity(firstName, lastName: string): string =
  case firstName
  of "Damien": return "Tokyo"
  of "Alex": return "New York"
  else: return "Unknown"

proc getUserCity(userID: int): string =
  case userID
  of 1: return "Tokyo"
  of 2: return "New York"
  else: return "Unknown"

doAssert getUserCity("Damien", "Lundi") == "Tokyo"
doAssert getUserCity(2) == "New York" # -- Errata here: missing closing "

import sequtils
let numbers = @[1, 2, 3, 4, 5, 6]
let odd = filter(numbers, proc (x: int): bool = x mod 2 != 0)
doAssert odd == @[1, 3, 5]

import sequtils, sugar
let numbers1 = @[1, 2, 3, 4, 5, 6]
let odd1 = filter(numbers1, (x: int) -> bool => x mod 2 != 0)
assert odd1 == @[1, 3, 5]

proc isValid(x: int, validator: proc (x: int): bool) =
  if validator(x): echo(x, " is valid")
  else: echo(x, " is NOT valid")

import sugar
proc isValid2(x: int, validator: (x: int) -> bool) =
  if validator(x): echo(x, " is valid")
  else: echo(x, " is NOT valid")

var list: array[3, int]
list[0] = 1
list[1] = 42
assert list[0] == 1
assert list[1] == 42
assert list[2] == 0 #<1>

echo list.repr #<2>

# echo list[500]

var list2: array[-10 .. -9, int]
list2[-10] = 1
list2[-9] = 2

var list3 = ["Hi", "There"]

var list4 = ["My", "name", "is", "Dominik"]
for item in list4:
  echo(item)

for i in list4.low .. list4.high:
  echo(list4[i])

var list5: seq[int] = @[]
doAssertRaises(IndexDefect):
  list5[0] = 1

list5.add(1)

assert list5[0] == 1
doAssertRaises(IndexDefect):
  echo list5[42]

# -- Errata: var list: seq[int]; echo(list[0]). This now creates an exception,
# --         not a SIGSEGV.

block:
  var list = newSeq[string](3)
  assert list[0].len == 0
  list[0] = "Foo"
  list[1] = "Bar"
  list[2] = "Baz"

  list.add("Lorem")

block:
  let list = @[4, 8, 15, 16, 23, 42]
  for i in 0 ..< list.len:
    stdout.write($list[i] & " ")

var collection: set[int16]
doAssert collection == {}

block:
  let collection = {'a', 'x', 'r'}
  doAssert 'a' in collection

block:
  let collection = {'a', 'T', 'z'}
  let isAllLowerCase = {'A' .. 'Z'} * collection == {}
  doAssert(not isAllLowerCase)

let age = 10
if age > 0 and age <= 10:
  echo("You're still a child")
elif age > 10 and age < 18:
  echo("You're a teenager")
else:
  echo("You're an adult")

let variable = "Arthur"
case variable
of "Arthur", "Zaphod", "Ford":
  echo("Male")
of "Marvin":
  echo("Robot")
of "Trillian":
  echo("Female")
else:
  echo("Unknown")

let ageDesc = if age < 18: "Non-Adult" else: "Adult"

block:
  var i = 0
  while i < 3:
    echo(i)
    i.inc

block label:
  var i = 0
  while true:
    while i < 5:
      if i > 3: break label
      i.inc

iterator values(): int =
  var i = 0
  while i < 5:
    yield i
    i.inc

for value in values():
  echo(value)

import os
for filename in walkFiles("*.nim"):
  echo(filename)

for item in @[1, 2, 3]:
  echo(item)

for i, value in @[1, 2, 3]: echo("Value at ", i, ": ", value)

doAssertRaises(IOError):
  proc second() =
    raise newException(IOError, "Somebody set us up the bomb")

  proc first() =
    second()

  first()

block:
  proc second() =
    raise newException(IOError, "Somebody set us up the bomb")

  proc first() =
    try:
      second()
    except:
      echo("Cannot perform second action because: " &
        getCurrentExceptionMsg())

  first()

block:
  type
    Person = object
      name: string
      age: int

  var person: Person
  var person1 = Person(name: "Neo", age: 28)

block:
  type
    PersonObj = object
      name: string
      age: int
    PersonRef = ref PersonObj

  # proc setName(person: PersonObj) =
  #   person.name = "George"

  proc setName(person: PersonRef) =
    person.name = "George"

block:
  type
    Dog = object
      name: string

    Cat = object
      name: string

  let dog: Dog = Dog(name: "Fluffy")
  let cat: Cat = Cat(name: "Fluffy")

block:
  type
    Dog = tuple
      name: string

    Cat = tuple
      name: string

  let dog: Dog = (name: "Fluffy")
  let cat: Cat = (name: "Fluffy")

  echo(dog == cat)

block:
  type
    Point = tuple[x, y: int]
    Point2 = (int, int)

  let pos: Point = (x: 100, y: 50)
  doAssert pos == (100, 50)

  let pos1: Point = (x: 100, y: 50)
  let (x, y) = pos1 #<1>
  let (left, _) = pos1
  doAssert x == pos1[0]
  doAssert y == pos1[1]
  doAssert left == x

block:
  type
    Color = enum
      colRed,
      colGreen,
      colBlue

  let color: Color = colRed

block:
  type
    Color {.pure.} = enum
      red, green, blue

  let color = Color.red