The most asked Nim interview questions with structured answers — a quick answer, a clear explanation and working code for each. Covers basics for freshers through advanced, scenario and coding questions for experienced developers.
Updated November 2026 Reviewed by Abhishek Kumar 120 min read
100 Nim interview questions, grouped by level: freshers, intermediate, experienced and coding.
Every answer starts with a one-line “Quick answer” you can say out loud, followed by the explanation and runnable code.
Use the filter bar to practise only the level you are interviewing for, then test yourself with the free Nim quiz.
What is Nim, and why do interviewers ask about it?
This page provides a complete collection of Nim Interview Questions and Answers designed for software developers, system programmers, competitive programmers, and candidates preparing for programming language interviews.
Nim is a modern, statically typed compiled programming language designed for performance, efficiency, and developer productivity. It combines features from multiple programming paradigms including procedural, object-oriented, and functional programming.
This interview guide covers beginner, intermediate, and advanced Nim concepts including syntax, variables, data types, procedures, generics, macros, memory management, object-oriented programming, concurrency, compilation, and real-world programming scenarios.
Why companies hire for Nim
High performance – compiles to C, C++, and JavaScript with zero-cost abstractions
Powerful macro system – metaprogramming capabilities for code generation and DSLs
Quick answerNim is a statically typed, compiled programming language that combines performance with expressive syntax. It features a powerful macro system, multiple memory management options, and compiles to C, C++, and JavaScript.
Statically typed – type checking at compile time
Compiled – to efficient native code
Macros – advanced metaprogramming
Garbage collected (or manual via --gc:arc)
Multi‑paradigm – procedural, OOP, functional
Nim
# Hello World in Nim
echo "Hello, World!"# Using a procedureproc greet(): string =
return"Hello, World!"
echo greet()
Quick answerSets are unordered collections of distinct elements. They are efficient for membership tests.
Declaration: var s: set[char]
Initialization: var s = {'a', 'b', 'c'}
Add: s.incl('d')
Remove: s.excl('a')
Membership: 'b' in s
Nim
# Null safety in Nim (using Option and Result)import std/options
import std/result# Option typevar nullable_string: Option[string] = none(string)
var non_nullable_string: string = "Hello"# Safe access with ifif nullable_string.isSome:
echo "String is: ", nullable_string.get()
echo "Length: ", nullable_string.get().len
# Elvis operator equivalent (using get)let value = nullable_string.get("default")
# Safe navigation using get with defaulttypePerson = object
name: stringvar person = Person(name: "Alice")
# Using get with default for missing fields (not applicable in Nim, but we can use a helper)proc getAttr[T](obj: T, field: string): string = ""# Not idiomatic# Using Result for safe operationsproc safeLength(s: Option[string]): Result[int, string] =
if s.isSome:
ok(s.get().len)
else:
err("No string")
# Usage
echo value
echo safeLength(some("hello")).get(0)
Quick answerTables are associative arrays (hash maps) mapping keys to values.
Creation: var t = {1: "one", 2: "two"}.toTable
Access: t[1]
Add/Update: t[3] = "three"
Contains: t.hasKey(2)
Iteration: for k, v in t: echo k, " ", v
Nim
# Control Flow in Nim# If-elsevar age = 25var status: stringif age < 18:
status = "Minor"else:
status = "Adult"
echo status
# If-elif-elsevar grade = 'A'
varresult: stringif grade == 'A':
result = "Excellent"elif grade == 'B':
result = "Good"elif grade == 'C':
result = "Fair"else:
result = "Needs Improvement"
echo result# For loopfor i in0..4:
echo i
# For loop with step (using countup with step)for i in countup(1, 9, 2):
echo i
# For loop descendingfor i in countdown(10, 1):
echo i
# While loopvar i = 0while i < 5:
echo i
inc(i)
# Do-while (using while with break)
i = 0whiletrue:
echo i
dec(i)
if i <= 0:
break# For loop with items and pairsvar items = @['a', 'b', 'c']
for index, item in items:
echo index, ": ", item
Quick answerObjects are composite types that group fields. They support inheritance and can have methods.
Definition: type Person = object name: string; age: int
Instantiation: var p = Person(name: "Alice", age: 30)
Field access: p.name
Inheritance: type Employee = object of Person
Nim
# Lambda Expressions (Anonymous Procedures)# Basic lambdalet square = proc(x: int): int = x * x
# Lambda with multiple parameterslet doubled = proc(x: int): int = x * 2# Higher-order proceduresproc performOperation(x, y: int, operation: proc(a, b: int): int): int =
return operation(x, y)
# Lambda with multiple lines (using block)let complex = proc(x: int): int =
let y = x * 2return y + 10# Function referenceproc multiply(x, y: int): int = x * y
let multiplyRef = multiply
# Returning lambda from procedureproc getOperation(opType: string): proc(a, b: int): int =
case opType
of"add": returnproc(a, b: int): int = a + b
of"subtract": returnproc(a, b: int): int = a - b
else: returnproc(a, b: int): int = 0# Usage
echo square(5)
echo performOperation(10, 20, proc(a, b: int): int = a * b)
let add = getOperation("add")
echo add(5, 3)
# Lambda with filter and map (using sequtils)import sequtils
var numbers = @[1, 2, 3, 4, 5]
let filtered = numbers.filter(proc(x: int): bool = x > 2)
let mapped = numbers.map(proc(x: int): int = x * 2)
echo filtered
echo mapped
Multimethods: dynamic dispatch on multiple arguments
Nim
# Scope Functions (using templates and with)# Nim doesn't have built-in scope functions like Kotlin, but we can use templates.# let - execute block (using a template)template letScope(body: untyped): untyped =
let x = body
x
# Usageletresult = letScope:
var y = 10
y * 2
echo result# apply - configure object (using with)typePerson = object
name: string
age: intproc updatePerson(p: varPerson) =
p.age += 1var person = Person(name: "Alice", age: 25)
person.updatePerson()
echo person.age
# also - perform additional operations (using a proc)proc also[T](x: T, f: proc(x: var T)): T =
var y = x
f(y)
return y
let newPerson = also(person, proc(p: varPerson) = p.age += 1)
echo newPerson.age
# take-if equivalentproc takeIf[T](cond: proc(x: T): bool, value: T): Option[T] =
if cond(value): some(value) else: none(T)
let ageOk = takeIf(proc(x: int): bool = x >= 18, 25)
if ageOk.isSome:
echo "Valid age"
Quick answervar: mutable variable, evaluated at runtime let: immutable variable, evaluated at runtime const: compile‑time constant, must be known at compile time
var: mutable variable, evaluated at runtime
let: immutable variable, evaluated at runtime
const: compile‑time constant, must be known at compile time
Nim
# Extension Functions in Nim# Nim doesn't have extension functions directly, but we can use converters or wrapper procs.# String extensionsproc isEmail(s: string): bool =
return '@' in s and '.' in s
proc addPrefix(s: string, prefix: string): string =
return prefix & s
# Numeric extensionsproc isEven(n: int): bool = n mod2 == 0proc isOdd(n: int): bool = n mod2 != 0# List extensions (using seq)proc secondOrNone[T](s: seq[T]): Option[T] =
if s.len >= 2: some(s[1]) else: none(T)
# String word countproc wordCount(s: string): int =
return s.splitWhitespace.len
# Monkey patching (using converters, not recommended)# Instead, we can use a wrapper typetypeMyString = distinctstringproc isEmail(s: MyString): bool =
return '@' instring(s) and '.' instring(s)
# Usage
echo "test@example.com".isEmail()
echo addPrefix("Hello", "Greeting: ")
echo 5.isEven()
echo wordCount("Hello World")
echo secondOrNone(@[1, 2, 3]).get(0)
Quick answerNim infers types from the initial value, so explicit annotations are often optional.
Variable: let x = 42 → int
Procedure return: inferred from last expression
Generic types: inferred from usage
Nim
# Type Aliases in Nim# Type aliases using distinct types or simple type definitionstypeOperation = proc (a, b: int): intUserMap = Table[string, Table[string, string]]
UserId = intUserName = string# Usageproc add(a, b: int): int = a + b
proc multiply(a, b: int): int = a * b
proc execute(op: Operation, a, b: int): int =
return op(a, b)
# Complex type alias (tuple)typeUser = tuple[name: string, age: int] # (name, age)var users: Table[string, User] # using table
users["user1"] = (name: "Alice", age: 25)
users["user2"] = (name: "Bob", age: 30)
# Function type aliastypeStringPredicate = proc(s: string): boolproc filterStrings(strings: seq[string], pred: StringPredicate): seq[string] =
result = @[]
for s in strings:
if pred(s):
result.add(s)
# Usage
echo execute(add, 5, 3)
echo execute(multiply, 5, 3)
echo users["user1"].name
Quick answerUse import to bring symbols from other modules. You can also use from and export.
Simple: import math
Specific: from math import sqrt, PI
Alias: import times as t
Export: export mymodule
Nim
# Inline Functions (using templates or macros)# Nim doesn't have inline functions per se, but templates are similar.# Timing decorator (using template)import times
template measureTime(body: untyped): untyped =
let start = cpuTime()
body
let elapsed = cpuTime() - start
echo "Time: ", elapsed, "s"# Usage
measureTime:
sleep(100)
echo "Done"# Reified type parameter (using generic types)proc isType[T](value: T, typ: typedesc): bool =
return value is typ
# Filter by typeproc filterByType[T](lst: seq[RootObj], typ: typedesc[T]): seq[T] =
result = @[]
for item in lst:
when compiles(item is T):
if item is T:
result.add(item)
# Usage
echo isType("Hello", string)
echo isType(42, int)
var mixed: seq[RootObj] = @[1, 2, "Hello", 3.14, "World"] # not allowed; use object variants# Inline function using lambda (single expression)let square = proc(x: int): int = x * x
# Higher-Order Functions in Nim# Function that takes a function as parameterproc applyOperation(a, b: int, operation: proc(x, y: int): int): int =
return operation(a, b)
# Function that returns a functionproc getMultiplier(factor: int): proc(x: int): int =
returnproc(x: int): int = x * factor
# Function compositionproc compose[A,B,C](f: proc(x: B): C, g: proc(x: A): B): proc(x: A): C =
returnproc(x: A): C = f(g(x))
# Higher-order function with multiple lambdasproc process(value: int, transform: proc(x: int): int, filterFunc: proc(x: int): bool): Option[int] =
if filterFunc(value):
return some(transform(value))
else:
return none(int)
# Usage with lambda
echo applyOperation(10, 20, proc(a, b: int): int = a + b)
let double = getMultiplier(2)
echo double(5)
let square = proc(x: int): int = x * x
let addTen = proc(x: int): int = x + 10let squareThenAddTen = compose(addTen, square)
echo squareThenAddTen(5)
# Using named functionproc add(a, b: int): int = a + b
echo applyOperation(10, 20, add)
# Built-in higher-order functions (using sequtils)import sequtils
var numbers = @[1, 2, 3, 4, 5]
let squared = numbers.map(proc(x: int): int = x * x)
let even = numbers.filter(proc(x: int): bool = x mod2 == 0)
let sumAll = numbers.foldl(a + b)
echo squared
echo even
echo sumAll
# Generators (Iterators) in Nim# Nim uses iterators instead of generators# Simple iteratoriterator simpleGenerator(n: int): int =
for i in1..n:
yield i
# Iterator with operationsiterator evenNumbers(n: int): int =
for i in0..<n:
if i mod2 == 0:
yield i
# Iterator with map (using transform)iterator doubleGenerator(iter: iterator(): int): int =
for value in iter():
yield value * 2# Filter iteratoriterator filterGenerator(iter: iterator(): int, pred: proc(x: int): bool): int =
for value in iter():
if pred(value):
yield value
# Usagefor i in simpleGenerator(5):
echo i
for i in evenNumbers(10):
echo i
# Collect from iterator into sequenceimport sequtils
let evens = toSeq(evenNumbers(10))
echo evens
# Async iterator (not directly, but use async procs with yield)
Quick answerMacros are powerful metaprogramming tools that operate on Nim’s abstract syntax tree (AST) at compile time, enabling code generation and DSLs.
Quick answernil represents a null reference for pointer and ref types. Dereferencing nil is undefined behavior.
Ref types: var p: ref int = nil
Check: if p != nil: echo p[]
Option types: prefer Option for safety
Nim
# Generics in Nim# Generic typetypeBox[T] = object
value: T
proc newBox[T](val: T): Box[T] =
Box[T](value: val)
proc getValue[T](box: Box[T]): T =
return box.value
# Generic procedureproc swap[T](a, b: var T) =
let tmp = a
a = b
b = tmp
# Generic with constraints (using type classes)proc sumItems[T: SomeNumber](items: seq[T]): T =
varresult: T = 0for item in items:
result += item
returnresult# Variance (Nim uses invariant generics by default)# Covariant not directly, but we can use inheritance with refstypeProducer[T] = object
data: T
proc produce[T](p: Producer[T]): T = p.data
# Contravariant (not directly, but we can use method overloading)# Usagevar box = newBox("Hello")
echo getValue(box)
var a = 1; var b = 2
swap(a, b)
echo a, " ", b
echo sumItems(@[1, 2, 3, 4, 5])
Quick answerref: garbage‑collected or traced pointer; safe, managed ptr: unmanaged pointer; unsafe, for low‑level code Memory: ref points to objects on heap (GC), ptr can point anywhere
ref: garbage‑collected or traced pointer; safe, managed
ptr: unmanaged pointer; unsafe, for low‑level code
Memory: ref points to objects on heap (GC), ptr can point anywhere
Nim
# Singleton Pattern in Nim# Using module-level variables (singleton by nature)# In a module app_config.nim:letAPI_URL* = "https://api.example.com"letTIMEOUT* = 5000proc printConfig*() =
echo "API URL: ", API_URL
echo "Timeout: ", TIMEOUT# Using a global variable with gettertypeAppConfig = object
apiUrl: string
timeout: intvar instance: AppConfigproc getAppConfig(): AppConfig =
if instance.apiUrl == "":
instance = AppConfig(apiUrl: "https://api.example.com", timeout: 5000)
return instance
# Using a type with a static field (not directly, but can use a ref and a proc)typeAppConfigRef = refobject
apiUrl: string
timeout: intvar appConfigInstance: AppConfigRefproc getAppConfigRef(): AppConfigRef =
if appConfigInstance.isNil:
appConfigInstance = AppConfigRef(apiUrl: "https://api.example.com", timeout: 5000)
return appConfigInstance
# Using a constructor with a global variablevar config: AppConfigproc initConfig() =
if config.apiUrl == "":
config = AppConfig(apiUrl: "https://api.example.com", timeout: 5000)
# Usage
initConfig()
echo config.apiUrl
Quick answerNim’s garbage collector (GC) manages memory automatically. The default is ORC (since Nim 1.6), which is a cycle‑collecting reference counting system.
ORC: efficient, low latency, no stop‑the‑world
ARC: simple reference counting
Refc: older, with cycle detection via GC
Nim
# Decorators (using templates and macros)# Nim doesn't have decorators like Python, but we can use templates or macros.# Basic decorator (using template)template myDecorator(body: untyped): untyped =
echo "Before function"
body
echo "After function"# Usage
myDecorator:
echo "Hello"# Decorator with parameters (using macro)import macros
macro repeatDecorator(n: int, body: untyped): untyped =
result = newStmtList()
for i in0..<n:
result.add(body)
# Usage
repeatDecorator(3):
echo "Hello!"# Class decorator (using a macro)macro addMethod(cls: typedesc): untyped =
let newMethod = quote do:
proc newMethod(self: `cls`): string =
return"New method added"result = newStmtList(newMethod)
# UsagetypeMyClass = object
addMethod(MyClass)
var obj = MyClass()
echo obj.newMethod()
# Property decorator (using getter/setter)typePerson = object
name: stringproc name(p: Person): string = p.name
proc `name=`(p: varPerson, value: string) = p.name = value
# Usagevar p = Person(name: "Alice")
echo p.name
p.name = "Bob"
echo p.name
# Generators and Iterators (already covered in Q22)# Just an additional example with custom iteratoriterator fibonacci(n: int): int =
var a = 0; var b = 1for i in0..<n:
yield a
(a, b) = (b, a + b)
iterator evenNumbers(n: int): int =
for i in0..<n:
if i mod2 == 0:
yield i
# Custom iterator with send (using closure iterator)iterator accumulator(): int =
var total = 0whiletrue:
let value = yield total
if value == -1: break
total += value
# Usagefor i in fibonacci(10):
echo i
for i in evenNumbers(10):
echo i
# Using closure iteratorvar acc = accumulator()
echo acc() # start
echo acc(10) # total = 10
echo acc(20) # total = 30
# Descriptors in Nim (using getter/setter)# Nim doesn't have descriptors, but we can use properties with getter/setter.typePerson = object
age: intproc age(p: Person): int = p.age
proc `age=`(p: varPerson, value: int) =
if value < 0:
raise newException(ValueError, "Age must be positive")
p.age = value
# Property with validationtypePositiveNumber = object
value: intproc setPositive(n: varPositiveNumber, val: int) =
if val < 0:
raise newException(ValueError, "Must be positive")
n.value = val
proc getPositive(n: PositiveNumber): int = n.value
# Usagevar p = Person(age: 25)
echo p.age
p.age = 30try:
p.age = -5exceptValueError:
echo "Invalid age"
Quick answerThe system module is implicitly imported and provides core functionality like echo, len, add, memory management, etc.
Built‑in: echo, quit
Memory: alloc, dealloc
Type helpers: typeof, addr
Nim
# Remove duplicatesproc removeDuplicates[T](arr: seq[T]): seq[T] =
var seen: HashSet[T]
result = @[]
for item in arr:
if item notin seen:
seen.incl(item)
result.add(item)
echo removeDuplicates(@[1, 2, 2, 3, 3, 4]) # [1, 2, 3, 4]# Using a set (preserves order not guaranteed)proc removeDuplicatesSet[T](arr: seq[T]): seq[T] =
result = toSeq(union(arr))
# Using list comprehension (not directly, but we can filter)proc removeDuplicatesComprehension[T](arr: seq[T]): seq[T] =
var seen: HashSet[T]
arr.filterIt(if it notin seen: (seen.incl(it); true) else: false)
Quick answerrandom provides random number generation.
Seed: randomize()
Rand: rand(100) (0..100)
Float: rand(1.0)
Nim
# Loop through dictionary (table)import tables
proc loopDict(d: Table[string, string]) =
for key, value in d:
echo key, " => ", value
# Using pairsproc loopDictPairs(d: Table[string, string]) =
for (key, value) in d:
echo key, " => ", value
# Loop through keysproc loopDictKeys(d: Table[string, string]) =
for key in keys(d):
echo key, " => ", d[key]
var data = {"name": "Alice", "age": "25", "city": "NYC"}.toTable
loopDict(data)
Quick answerMetaprogramming in Nim includes macros, templates, compile‑time evaluation, and pragmas to generate or transform code.
Macros: AST manipulation
Templates: simple substitution
Pragmas: compiler directives
Static: compile‑time code execution
Nim
# Factorialproc factorial(n: int): int =
if n <= 1: 1else: n * factorial(n-1)
echo factorial(5) # 120# Iterativeproc factorialIterative(n: int): int =
result = 1for i in2..n:
result *= i
# Using math (not built-in, but can implement)# no built-in factorial, but we can use our own
Quick answerDSLs in Nim are often built using templates, macros, and the with pattern. For example, a SQL or HTML builder.
Template: template html(body) = "<html>" & body & "</html>"
Macro: parse custom syntax at compile time
Fluent interface: method chaining
Nim
# Fibonacciproc fibonacci(n: int): int =
if n <= 1: n
else: fibonacci(n-1) + fibonacci(n-2)
echo fibonacci(8) # 21# Iterativeproc fibonacciIterative(n: int): int =
if n <= 1: return n
var a = 0; var b = 1for i in2..n:
(a, b) = (b, a + b)
return b
# Memoized version (using a table)import tables
proc fibonacciMemo(n: int, memo: varTable[int, int]): int =
if n in memo: return memo[n]
if n <= 1: return n
result = fibonacciMemo(n-1, memo) + fibonacciMemo(n-2, memo)
memo[n] = resultvar memo = initTable[int, int]()
echo fibonacciMemo(10, memo)
Quick answerNim’s effect system tracks side effects (e.g., I/O, exceptions) and can enforce purity with the {.noSideEffect.} pragma.
Effects: io, time, write, exception
Pragma: {.noSideEffect.} ensures pure
Tag: {.effects.} for custom effects
Nim
# FizzBuzzproc fizzbuzz(n: int) =
for i in1..n:
if i mod15 == 0:
echo "FizzBuzz"elif i mod3 == 0:
echo "Fizz"elif i mod5 == 0:
echo "Buzz"else:
echo i
fizzbuzz(15)
# Return seqproc fizzbuzzList(n: int): seq[string] =
result = @[]
for i in1..n:
if i mod15 == 0:
result.add("FizzBuzz")
elif i mod3 == 0:
result.add("Fizz")
elif i mod5 == 0:
result.add("Buzz")
else:
result.add($i)
Quick answerUse threadvar to declare thread‑local variables. Each thread gets its own copy.
Declaration: threadvar counter: int
Access: each thread sees its own counter
Safe: no locking needed for per‑thread data
Nim
# Find missing numberproc findMissing(arr: seq[int]): int =
let n = arr.len + 1let total = n * (n + 1) div2let sum = arr.foldl(a + b, 0)
return total - sum
echo findMissing(@[1, 2, 4, 5, 6]) # 3# Using XORproc findMissingXor(arr: seq[int]): int =
let n = arr.len + 1var xorSum = 0for i in1..n:
xorSum = xorSum xor i
for num in arr:
xorSum = xorSum xor num
return xorSum
Quick answerChannels (from std/channels) enable safe communication between threads.
Create: var chan: Channel[int]
Send: chan.send(42)
Receive: let x = chan.recv()
Nim
# Find duplicatesproc findDuplicates[T](arr: seq[T]): seq[T] =
var seen: HashSet[T]
var duplicates: HashSet[T]
for item in arr:
if item in seen:
duplicates.incl(item)
else:
seen.incl(item)
return toSeq(duplicates)
echo findDuplicates(@[1, 2, 3, 2, 4, 3]) # [2, 3]# Using a table to countimport tables
proc findDuplicatesCount[T](arr: seq[T]): seq[T] =
var counter = initCountTable[T]()
for item in arr:
counter.inc(item)
result = @[]
for k, v in counter:
if v > 1:
result.add(k)
Quick answerNim’s asynchronous I/O uses a reactor pattern via std/asyncdispatch to handle multiple events in a single thread.
Event loop: runForever()
Callbacks: addTimer, addRead
Non‑blocking: efficient I/O multiplexing
Nim
# Sum of arrayproc sumArray[T: SomeNumber](arr: seq[T]): T =
result = 0for num in arr:
result += num
echo sumArray(@[1, 2, 3, 4, 5]) # 15# Using foldlimport sequtils
echo foldl(@[1, 2, 3, 4, 5], a + b, 0)
Quick answerasyncdispatch is the core module for asynchronous I/O, providing an event loop and async procs.
Wait: waitFor(someAsyncProc())
Loop: runForever()
Timers: sleepAsync, addTimer
Nim
# Average of arrayproc averageArray[T: SomeNumber](arr: seq[T]): float =
if arr.len == 0: return0.0var total: float = 0.0for num in arr:
total += float(num)
return total / float(arr.len)
echo averageArray(@[1, 2, 3, 4, 5]) # 3.0# Using sum and lenproc averageArray2[T: SomeNumber](arr: seq[T]): float =
if arr.len == 0: return0.0returnfloat(foldl(arr, a + b, 0)) / float(arr.len)
Quick answerlet can be used inside blocks to create local immutable bindings that are not visible outside.
Block: block: let x = 10
Scope: x exists only inside the block
Nim
# Flatten nested array (Nim doesn't have nested seqs easily, but we can use a variant)# Using recursion with seq of some typeproc flattenArray(arr: seq[seq[int]]): seq[int] =
result = @[]
for sub in arr:
result.add(sub)
# For heterogeneous nesting, use a tagged union or a string representation.# Using a generic flatten with varargsproc flatten[T](arr: varargs[seq[T]]): seq[T] =
result = @[]
for sub in arr:
result.add(sub)
echo flatten(@[1, 2], @[3, 4]) # [1, 2, 3, 4]
Quick answerfloat: double precision (64‑bit) float32: single precision float64: same as float
float: double precision (64‑bit)
float32: single precision
float64: same as float
Nim
# Merge sortproc merge[T](left, right: seq[T]): seq[T] =
result = @[]
var i = 0; var j = 0while i < left.len and j < right.len:
if left[i] <= right[j]:
result.add(left[i]); inc i
else:
result.add(right[j]); inc j
result.add(left[i..^1])
result.add(right[j..^1])
proc mergeSort[T](arr: seq[T]): seq[T] =
if arr.len <= 1: return arr
let mid = arr.len div2let left = mergeSort(arr[0..<mid])
let right = mergeSort(arr[mid..^1])
return merge(left, right)
Quick answerjson provides parsing and serialization of JSON data.
Parse: let data = parseJson("{\"key\":\"value\"}")
Access: data["key"].getStr()
Generate: %*{"name": "Nim"}.pretty()
Nim
# Group by propertyimport tables
typeItem = object
kind: string
name: stringproc groupByProperty(items: seq[Item], key: string): Table[string, seq[Item]] =
result = initTable[string, seq[Item]]()
for item in items:
let keyVal = case key
of"kind": item.kind
else: ""if keyVal notinresult:
result[keyVal] = @[]
result[keyVal].add(item)
var data = @[
Item(kind: "fruit", name: "apple"),
Item(kind: "fruit", name: "banana"),
Item(kind: "veg", name: "carrot")
]
let groups = groupByProperty(data, "kind")
for k, v in groups:
echo k, ": ", v
Quick answerparseutils provides low‑level parsing functions like parseInt, parseFloat, etc.
Int: var x: int; discard parseInt("123", x)
Float: var y: float; discard parseFloat("3.14", y)
Nim
# Deep clone objectimport std/objutils
# Using a generic deepCopy proc (not built-in, we'll implement a simple one)proc deepClone[T](x: T): T =
# Works for simple types, but for refs and objects we need custom handlingreturn x
# For objects with references, we can use a custom proceduretypeAddress = object
city: string
zip: stringUser = refobject
name: string
address: Addressproc deepCloneUser(u: User): User =
result = User(name: u.name, address: u.address) # shallow copy for address# Usagevar original = User(name: "Alice", address: Address(city: "NYC", zip: "10001"))
var cloned = deepCloneUser(original)
cloned.name = "Bob"
echo original.name # Alice
echo cloned.name # Bob
Quick answeruri provides parsing and construction of URIs/URLs.
Parse: let u = parseUri("https://nim-lang.org/")
Access: u.scheme, u.hostname
Nim
# Pipe function (using a template)template pipe(value, body: untyped): untyped =
varresult = value
body
result# Usageproc double(x: int): int = x * 2proc addTen(x: int): int = x + 10proc square(x: int): int = x * x
letresult = pipe(5):
result = double(result)
result = addTen(result)
result = square(result)
echo result# 400# Alternatively, using proc compositionproc compose[A,B,C](f: proc(x: B): C, g: proc(x: A): B): proc(x: A): C =
returnproc(x: A): C = f(g(x))
let process = compose(square, compose(addTen, double))
echo process(5) # 400
# Compose function (reverse of pipe)proc composeReverse[A,B,C](f: proc(x: B): C, g: proc(x: A): B): proc(x: A): C =
returnproc(x: A): C = f(g(x))
proc double(x: int): int = x * 2proc addTen(x: int): int = x + 10proc square(x: int): int = x * x
let process = composeReverse(square, composeReverse(addTen, double))
echo process(5) # (5*2+10)^2 = 400
# Memoization (using a table)import tables
proc memoize[T, R](f: proc(x: T): R): proc(x: T): R =
var cache = initTable[T, R]()
returnproc(x: T): R =
if x in cache:
return cache[x]
else:
letresult = f(x)
cache[x] = resultreturnresultproc fib(n: int): int =
if n <= 1: n
else: fib(n-1) + fib(n-2)
let memoFib = memoize(fib)
echo memoFib(10)
# Using a built-in caching macro? Not standard, but we can use a closure.
Quick answerwhen is a compile‑time conditional similar to if, but evaluated during compilation.
Usage: when defined(windows): ...
Static: branches that are not taken are not compiled
Nim
# Once function (using a global flag)proc once(f: proc(): string): proc(): string =
var called = falsevarresult: stringreturnproc(): string =
ifnot called:
called = trueresult = f()
returnresultproc initialize(): string =
echo "Initialized"return"App initialized"let initOnce = once(initialize)
echo initOnce() # prints "Initialized" and "App initialized"
echo initOnce() # prints "App initialized" again, no re-init
Quick answerstatic: blocks execute code at compile time. Useful for initializing compile‑time data.
Syntax: static: echo "Compile time"
Result: can define constants
Nim
# Debounce with leading edge (not built-in, but can use a timer)import std/asyncdispatch
import std/times
proc debounceLeading(delayMs: int, action: proc()) {.async.} =
var lastCall = 0whiletrue:
let now = cpuTime() * 1000if now - lastCall >= delayMs:
lastCall = now
action()
await sleepAsync(1)
# Usageproc printHello() = echo "Hello"# This would run in an async loop; not a simple function, so we skip practical usage.
Quick answer{.compileTime.} marks a procedure to be executed at compile time, enabling CTFE.
Mark: proc compute(): int {.compileTime.} = ...
Use: const x = compute()
Nim
# Throttle with leading edge (similar to debounce)proc throttleLeading(delayMs: int, action: proc()) {.async.} =
var lastCall = 0whiletrue:
let now = cpuTime() * 1000if now - lastCall >= delayMs:
lastCall = now
action()
await sleepAsync(1)
# Usage would be similar to debounce.
Quick answerNim allows creating custom literal suffixes using the suffix pragma.
Define: proc \`"kg"\`(x: int): int = x * 1000
Usage: 5.kg
Nim
# Deep equal (using a recursive proc)proc deepEqual(a, b: any): bool =
# This is a simplified version; for complex types, we need more.if a.type != b.type: returnfalsewhen a.typeisstringor a.typeisintor a.typeisfloat:
return a == b
elif a.typeisseq:
if a.len != b.len: returnfalsefor i in0..<a.len:
ifnot deepEqual(a[i], b[i]): returnfalsereturntrueelif a.typeisTable:
if a.len != b.len: returnfalsefor key in keys(a):
ifnot deepEqual(a[key], b[key]): returnfalsereturntrueelif a.typeisobject:
for field in fields(a):
ifnot deepEqual(a.field, b.field): returnfalsereturntrueelse:
return a == b
# Usagelet obj1 = (name: "Alice", address: (city: "NYC"))
let obj2 = (name: "Alice", address: (city: "NYC"))
echo deepEqual(obj1, obj2) # true
# Iterator pattern (using Nim's built-in iterators)# We already have iterators. This is just an example of custom iterator.iterator myRange(start, stop: int): int =
for i in start..stop:
yield i
# Usagefor i in myRange(1, 5):
echo i
# Custom collection with iteratortypeMyCollection = object
items: seq[string]
proc add(c: varMyCollection, item: string) =
c.items.add(item)
iterator items(c: MyCollection): string =
for item in c.items:
yield item
# Usagevar c = MyCollection()
add(c, "A"); add(c, "B"); add(c, "C")
for item in c.items:
echo item
Nim is a statically typed compiled programming language designed for performance, efficiency, and expressiveness. It combines features from languages like Python, Ada, and C while providing fast native execution.
What are the main features of Nim?
Nim features include efficient compilation, static typing, metaprogramming, macros, generics, automatic memory management, powerful syntax, and support for concurrent programming.
What are procedures in Nim?
Procedures in Nim are reusable blocks of code that perform specific tasks. They can accept parameters, return values, and support features such as type checking and optimization.
What are macros in Nim?
Nim macros allow developers to perform compile-time code transformations and extend the language by generating or modifying program code during compilation.
What are generics in Nim?
Generics in Nim allow developers to write reusable code that works with multiple data types while maintaining type safety and performance.
How does memory management work in Nim?
Nim provides automatic memory management using garbage collection and also supports advanced memory management techniques for performance-critical applications.
What are iterators in Nim?
Iterators in Nim provide a way to generate sequences of values one at a time, allowing efficient processing of collections without creating unnecessary memory overhead.
How does concurrency work in Nim?
Nim supports concurrency through features such as threads, asynchronous programming, and message passing, allowing developers to build scalable applications.
Why are Nim interview questions important?
Nim interview questions evaluate understanding of modern programming concepts including syntax, memory management, metaprogramming, generics, concurrency, and performance optimization.
How can I prepare for a Nim interview?
Practice Nim syntax, data types, procedures, iterators, macros, templates, generics, memory management, concurrency concepts, and solve practical Nim programming problems.
AK
Written and reviewed by Abhishek Kumar
Founder, InterviewPitch · 10+ years in IT. Questions are collected from real interview rounds and refreshed regularly. Spotted an error? Tell us.