Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 36 ยท Projects and Practice

Nim Practice Problems: Objects, Memory and Tooling

Test what you learned in Nim with practice problems on objects, variants, generics, templates, memory, concurrency and FFI, with hints and runnable C checks.

Reading is not enough: skills come from writing code. This page gives you problems for each topic of the second half of the course, with hints and a worked solution for some. Try each in your own Nim installation first; the Nim code on this site is read-only because the compiler is not available here. Where a problem has a runnable C check (a stand-in), you can use it to verify the logic or the expected numbers.

Work in order, and look at hints only after a real attempt.

Objects and generics

1. Shapes. Define Shape as a ref object of RootObj with Circle and Rect children and a method area. Put three shapes in a seq[Shape] and print the total area. See Inheritance and Methods.

Hint: the base method needs {.base.}.

2. Expression variant. Model Num(float), Add(left, right) and Mul(left, right) as a variant object and write eval. Add Neg and watch the compiler point out the case statements you must update. See Variant Objects and Enums.

Check: the C stand-in evaluates (2 + 3) * 4, which you should get as 20.

C C check: evaluate (2 + 3) * 4 with a tagged tree

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

3. Generic stack and queue. Write Stack[T] and Queue[T] with push, pop, len and an items iterator. Constrain a sumAll proc to SomeNumber. See Generics and Concepts.

Macros and templates

4. A check template. Write template check(cond: untyped) that prints ok: <source> or FAILED: <source> using astToStr(cond). See Templates.

5. unroll macro. Write a macro that expands unroll(4): echo "x" into four echo calls. See Macros and the AST.

6. Compile-time table. Build a const array of the first 16 powers of two with a loop in a block: and use static to assert its last entry is 32768. See Compile-Time Execution.

Check: confirm the expected number first.

C C check: the sixteenth power of two

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Memory and concurrency

7. Cycle or not? Build a doubly linked list of ref object nodes under --mm:arc and under --mm:orc. Explain which one can leak and why. See Memory Management with ARC and ORC.

8. Move-only handle. Write a FileHandle object with =destroy and a =copy marked {.error.}, so copying does not compile. See Value, Reference and Pointer Semantics.

9. Parallel sum. Split an array of one million integers into four chunks, sum each in a thread, send the partial sums through a channel and add them. See Threads and Channels.

Check: the answer for the numbers 1 to 1,000,000 is 500000500000. This C check uses four threads and joins them.

C C check: sum with four threads

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

10. Two async tasks. Write two async procs that each sleepAsync a different time and print when they finish. Run them with all and predict the order and the total time. See Async and Await.

FFI and tooling

11. Wrap strlen and toupper. Import them with importc and call them on a cstring. Why must the cstring outlive the call? See Calling C from Nim.

12. A package. Create a library with nimble init, add a task that runs a formatter command, write three tests and add a requires line with a lower bound. See Nimble and Packages.

13. Failing on purpose. Write a unittest suite for a function that parses "12:34" into minutes, with tests for a bad format, a negative number and midnight. Use expect for errors. See Testing and Debugging.

Check: the expected value for "12:34" is 754 minutes.

C C check: minutes since midnight

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Bigger challenges

  1. Extend the word counter to read a file and ignore a stop-word list.
  2. Add variables and ^ to the calculator.
  3. Make the ring buffer thread safe, and compare lock-based and atomic versions.
  4. Write a macro that generates a toString proc for any object by walking its fields.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which tool is right when you must inspect a syntax tree?

    Only macros receive the AST as a NimNode.
  2. 2. A cyclic structure leaks under which memory manager?

    ARC counts never reach zero in a cycle; ORC adds cycle collection.
  3. 3. Why use channels for sharing between threads?

    Messages have one owner at a time.
  4. 4. What must a callback passed to C use?

    The C calling convention is required for C to call the proc.

Summary

  • Practice each topic with a small program of your own, then combine them in projects.
  • Use the compiler's errors as feedback, especially for variants and generics.
  • Check numeric expectations independently, as the C checks do.
  • Keep tests next to the code and run nimble test.

Congratulations on finishing this part of the course.

Next: Back to the Nim track