{
  "id": "enwiki-001373964635",
  "slug": "nim-programming-language",
  "title": "Nim (programming language)",
  "qid": "",
  "lead": "Nim is a general-purpose, multi-paradigm, statically typed, compiled, high-level system programming language. It was designed and developed by a team led by Andreas Rumpf. Nim aims to be \"efficient, expressive, and elegant\", and supports metaprogramming, functional, message passing, procedural, and object-oriented programming paradigms. Nim includes features such as compile-time code generation, algebraic data types, and a foreign function interface (FFI) for interfacing with C, C++, Objective-C, and JavaScript. It also supports compilation to these same languages as intermediate representations.",
  "body": "Nim is a general-purpose, multi-paradigm, statically typed, compiled, high-level system programming language. It was designed and developed by a team led by Andreas Rumpf. Nim aims to be \"efficient, expressive, and elegant\", and supports metaprogramming, functional, message passing, procedural, and object-oriented programming paradigms. Nim includes features such as compile-time code generation, algebraic data types, and a foreign function interface (FFI) for interfacing with C, C++, Objective-C, and JavaScript. It also supports compilation to these same languages as intermediate representations. Let's declare a function that takes any type of number and displays its double In Nim functions with side effect are called \"proc\" proc timesTwo(i: SomeNumber) = echo i * 2 Let's write another function that takes any ordinal type, and returns the double of the input in its original type, if it is a number; or returns the input itself otherwise. We use a generic Type(T), and precise that it can only be an Ordinal func twiceIfIsNumber[T: SomeOrdinal](i: T): T = when T is SomeNumber: # A `when` is an `if` evaluated during compile time result = i * 2 # You can also write `return i * 2` else: # If the Ordinal is not a number it is converted to int, # multiplied by two, and reconverted to its based type result = (i.int * 2).T echo twiceIfIsNumber(67) # Passes an int to the function echo twiceIfIsNumber(67u8) # Passes an uint8 echo twiceIfIsNumber(true) # Passes a bool (Which is also an Ordinal) echo \"hello world\" echo(\"hello world\") \"hello world\".echo() \"hello world\".echo echo(\"hello\", \" world\") \"hello\".echo(\" world\") \"hello\".echo \" world\" Nim is almost fully style-insensitive; two identifiers are considered equal if they only differ by capitalization and underscores, as long as the first characters are identical. This is to enable a mixture of styles across libraries: one user can write a library using snake_case as a convention, and it can be used by a different user in a camelCase style without issue. const useHttps = true assert useHttps == useHttps assert useHTTPS == useHttps assert use_https == useHttps type Type = object `int`: int let `object` = Type(`int`: 9) assert `object` is Type assert `object`.`int` == 9 var `var` = 42 let `let` = 8 assert `var` + `let` == 50 const `assert` = true assert `assert` echo(\"Hello, World!\") Procedures can be called with no parentheses echo \"Hello, World!\" Another version of \"Hello World\" can be accomplished by calling the write function with the stdout stream: stdout.write(\"Hello, World!\\n\") write(stdout, \"Hello, World!\\n\") proc fib(n: Natural): Natural = if n import std/strutils var n = 0 try: stdout.write \"Input positive integer number: \" n = stdin.readline.parseInt except ValueError: raise newException(ValueError, \"You must enter a positive number\") var fact = 1 for i in 2..n: fact = fact * i echo fact Using the module math from Nim's standard library: import std/math echo fac(x) proc reverse(s: string): string = for i in countdown(s.high, 0): result.add s[i] let str1 = \"Reverse This!\" echo \"Reversed: \", reverse(str1) One of Nim's more exotic features is the implicit result variable. Every procedure in Nim with a non-void return type has an implicit result variable that represents the value to be returned. In the for loop we see an invocation of countdown which is an iterator. If an iterator is omitted, the compiler will attempt to use an items iterator, if one is defined for the type specified. import gintro/[gtk, glib, gobject, gio] proc appActivate(app: Application) = let window = newApplicationWindow(app) window.title = \"GTK3 application with gobject introspection\" window.defaultSize = (400, 400) showAll(window) proc main = let app = newApplication(\"org.gtk.example\") connect(app, \"activate\", appActivate) discard run(app) main() This code requires the gintro module to work, which is not part of the standard library. To install the module gintro and many others you can use the tool nimble, which comes as part of Nim. To install the gintro module with nimble you do the following: nimble install gintro == Programming paradigms== import std/[sequtils, sugar] let powersOfTwo = @[1, 2, 4, 8, 16, 32, 64, 128, 256] proc filter[T](s: openArray[T], pred: T -> bool): seq[T] = result = newSeq[T]() for i in 0 .. 32) syntactic sugar for the above, provided as a macro from std/sugar echo powersOfTwo.filter(x => x > 32) proc greaterThan32(x: int): bool = x > 32 echo powersOfTwo.filter(greaterThan32) func binarySearch[T](a: openArray[T]; elem: T): int is short for... proc binarySearch[T](a: openArray[T]; elem: T): int {.noSideEffect.} {.experimental: \"strictFuncs\".} type Node = ref object le, ri: Node data: string func len(n: Node): int = # valid: len does not have side effects var it = n while it != nil: inc result it = it.ri func mut(n: Node) = let m = n # is the statement that connected the mutation to the parameter m.data = \"yeah\" # the mutation is here # Error: 'mut' can have side effects # an object reachable from 'n' is potentially mutated import std/[sequtils, sugar] let numbers = @[1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1] a and b are special identifiers in the foldr macro echo numbers.filter(x => x > 3).deduplicate.foldr(a + b) # 30 import std/tables type Value = uint64 Ident = string ExprKind = enum Literal, Variable, Abstraction, Application Expr = ref object case kind: ExprKind of Literal: litIdent: Value of Variable: varIdent: Ident of Abstraction: paramAbs: Ident funcAbs: Expr of Application: funcApp, argApp: Expr func eval(expr: Expr, context: var Table[Ident, Value]): Value = case expr.kind of Literal: return expr.litIdent of Variable: return context[expr.varIdent] of Application: case expr.funcApp.kind of Abstraction: context[expr.funcApp.paramAbs] = expr.argApp.eval(context) return expr.funcAbs.eval(context) else: raise newException(ValueError, \"Invalid expression!\") else: raise newException(ValueError, \"Invalid expression!\") type Animal = ref object of RootObj name: string age: int type Dog = ref object of Animal type Cat = ref object of Animal var animals: seq[Animal] = @[] animals.add(Dog(name: \"Sparky\", age: 10)) animals.add(Cat(name: \"Mitten\", age: 10)) for a in animals: assert a of Animal Subtyping relations can also be queried with the of keyword. type Socket* = ref object host: int # private, lacks export marker getter of host address proc host*(s: Socket): int = s.host setter of host address proc `host=`*(s: var Socket, value: int) = s.host = value var s: Socket new s assert s.host == 0 # same as host(s), s.host() s.host = 34 # same as `host=`(s, 34) import std/strformat type Person = ref object of RootObj name: string Student = ref object of Person Teacher = ref object of Person method introduce(a: Person) = raise newException(CatchableError, \"Method without implementation override\") method introduce(a: Student) = echo &\"I am a student named {a.name}!\" method introduce(a: Teacher) = echo &\"I am a teacher named {a.name}!\" let people: seq[Person] = @[Teacher(name: \"Alice\"), Student(name: \"Bob\")] for person in people: person.introduce() template genType(name, fieldname: untyped, fieldtype: typedesc) = type name = object fieldname: fieldtype genType(Test, foo, int) var x = Test(foo: 4566) echo(x.foo) # 4566 The genType is invoked at compile-time and a Test type is created. proc addThese[T](a, b: T): T = a + b echo addThese(1, 2) # 3 (of int type) echo addThese(uint8 1, uint8 2) # 3 (of uint8 type) we don't want to risk subtracting unsigned numbers! proc subtractThese[T: SomeSignedInt | float](a, b: T): T = a - b echo subtractThese(1, 2) # -1 (of int type) import std/sequtils constrained generics can also be directly on the parameters proc compareThese[T](a, b: string | seq[T]): bool = for (i, j) in zip(a, b): if i != j: return false One can further clarify which types the procedure will accept by specifying a type class (in the example above, SomeSignedInt ). import std/macros macro twice(arg: untyped): untyped = result = quote do: `arg` `arg` twice echo \"Hello world!\" The twice macro in this example takes the echo statement in the form of an abstract syntax tree as input. In this example we decided to return this syntax tree without any manipulations applied to it. But we do it twice, hence the name of the macro. The result is that the code gets rewritten by the macro to look like the following code at compile time: echo \"Hello world!\" echo \"Hello world!\" proc printf(formatstr: cstring) {.header: \" \", varargs.} printf(\"%s %d\\n\", \"foo\", 5) In this code the printf function is imported into Nim and then used. Basic example using 'console.log' directly for the JavaScript compiling target: proc log(args: any) {.importjs: \"console.log(@)\", varargs.} log(42, \"z\", true, 3.14) The JavaScript code produced by the Nim compiler can be executed with Node.js or a web browser. import std/locks var thr: array[0..4, Thread[tuple[a,b: int ] L: Lock proc threadFunc(interval: tuple[a,b: int]) {.thread.} = for i in interval.a..interval.b: acquire(L) # lock stdout echo i release(L) initLock(L) for i in 0..high(thr): createThread(thr[i], threadFunc, (i*10, i*10+5)) joinThreads(thr) Nim also has a channels module that simplifies passing data between threads. import std/os type CalculationTask = object id*: int data*: int CalculationResult = object id*: int result*: int var task_queue: Channel[CalculationTask] var result_queue: Channel[CalculationResult] proc workerFunc() {.thread.} = result_queue.open() while true: var task = task_queue.recv() result_queue.send(CalculationResult(id: task.id, result: task.data * 2)) var workerThread: Thread[void] createThread(workerThread, workerFunc) task_queue.open() task_queue.send(CalculationTask(id: 1, data: 13)) task_queue.send(CalculationTask(id: 2, data: 37)) while true: echo \"got result: \", repr(result_queue.recv()) import std/[asynchttpserver, asyncdispatch] chronos could also be alternatively used in place of asyncdispatch, with no other changes. var server = newAsyncHttpServer() proc cb(req: Request) {.async.} = await req.respond(Http200, \"Hello World\") waitFor server.serve(Port(8080), cb)",
  "categories": [
    "1868482",
    "20161863",
    "20284182",
    "20528537",
    "22905584",
    "22906685",
    "22979799",
    "22985424",
    "23230146",
    "23266194",
    "23603337",
    "23888906",
    "24153110",
    "24153113",
    "24745122",
    "24769764",
    "26220375",
    "28081657",
    "28081659",
    "3469643",
    "41309532",
    "50998678",
    "61575348",
    "63700320",
    "9229844"
  ],
  "license": "CC BY-SA 4.0",
  "source_uri": "https://en.wikipedia.org/w/index.php?oldid=1373964635",
  "content_hash": "",
  "created_at": null,
  "updated_at": 1788908364.0,
  "claims": [],
  "contradictions": [],
  "confidence": 0.6,
  "csl": {
    "id": "enwiki-001373964635",
    "type": "webpage",
    "title": "Nim (programming language)",
    "author": [
      {
        "family": "Anticloud FZ LLE",
        "literal": "Anticloud FZ LLE"
      }
    ],
    "container-title": "encyclopegia.org",
    "publisher": "Anticloud FZ LLE",
    "publisher-place": "Dubai, United Arab Emirates",
    "URL": "https://encyclopegia.org/a/nim-programming-language",
    "issued": {
      "date-parts": [
        [
          2026,
          11,
          20
        ]
      ]
    },
    "accessed": {
      "date-parts": [
        [
          2026,
          11,
          20
        ]
      ]
    },
    "license": "CC BY-SA 4.0",
    "DOI": "eo1:enwiki-001373964635",
    "isBasedOn": "https://en.wikipedia.org/w/index.php?oldid=1373964635",
    "note": "Immutable snapshot enwiki-001373964635"
  }
}