Nim (programming language)

Short description: Programming language

This article is missing information about Nim's history, language design, tools, and paradigms. Please expand the article to include this information. Further details may exist on the talk page. (June 2019)

|

Nim

The Nim crown logo

Paradigms| Multi-paradigm: compiled, concurrent, procedural, imperative, functional, object-oriented, meta
Designed by| Andreas Rumpf
Developer| Nim Lang Team[1]
First appeared| 2008; 16 years ago (2008)
Typing discipline| Static,[2] strong,[3] inferred, structural
Scope| Lexical
Implementation language| Nim (self-hosted)
Platform| IA-32, x86-64, ARM, Aarch64, RISC-V, PowerPC ...[4]
OS| Cross-platform[5]
Filename extensions| .nim, .nims, .nimble
Website| nim-lang.org
Influenced by
Ada, Modula-3, Lisp, C++, Object Pascal, Python, Oberon, Rust, ParaSail[6]

Nim is a general-purpose, multi-paradigm, statically typed, compiled high-level systems programming language,[7] designed and developed by a team around Andreas Rumpf. Nim is designed to be "efficient, expressive, and elegant",[8] supporting metaprogramming, functional, message passing,[9] procedural, and object-oriented programming styles by providing several features such as compile time code generation, algebraic data types, a foreign function interface (FFI) with C, C++, Objective-C, and JavaScript, and supporting compiling to those same languages as intermediate representations.

## Contents

* 1 Description
* 2 History
* 3 Language design
* 3.1 Syntax
* 3.2 Influence
* 3.3 Uniform Function Call Syntax
* 3.4 Identifier equality
* 3.5 Stropping
* 4 Compiler
* 4.1 Compiler options
* 4.2 Memory management
* 5 Development tools
* 5.1 Bundled
* 5.1.1 Nimble
* 5.1.2 c2nim
* 5.1.3 koch
* 5.1.4 nimgrep
* 5.1.5 nimsuggest
* 5.1.6 niminst
* 5.1.7 nimpretty
* 5.1.8 Testament
* 5.2 Other notable tools
* 5.2.1 choosenim
* 5.2.2 nimpy
* 5.2.3 pixie
* 5.2.4 nimterop
* 6 Libraries
* 6.1 Pure/impure libraries
* 6.2 Standard library
* 6.3 Use of other libraries
* 7 Examples
* 7.1 Hello world
* 7.2 Fibonacci
* 7.3 Factorial
* 7.4 Reversing a string
* 7.5 Graphical user interface
* 8 Programming paradigms
* 8.1 Functional programming
* 8.1.1 First-class functions
* 8.1.2 Side effects
* 8.1.3 Function composition
* 8.1.4 Algebraic data types and pattern matching
* 8.2 Object-oriented programming
* 8.2.1 Subtyping and inheritance
* 8.2.2 Method calls and encapsulation
* 8.2.3 Dynamic dispatch
* 8.3 Metaprogramming
* 8.3.1 Templates
* 8.3.2 Generics
* 8.3.3 Macros
* 8.4 Foreign function interface (FFI)
* 8.5 Parallelism
* 8.6 Concurrency
* 9 Community
* 9.1 Online
* 9.2 Conventions
* 10 See also
* 11 References
* 12 External links

## Description

Nim is statically typed.[10] It supports compile-time metaprogramming features such as syntactic macros and term rewriting macros.[11] Term rewriting macros enable library implementations of common data structures, such as bignums and matrices, to be implemented efficiently and with syntactic integration, as if they were built-in language facilities.[12] Iterators are supported and can be used as first class entities,[11] as can functions, allowing for the use of functional programming methods. Object-oriented programming is supported by inheritance and multiple dispatch. Functions can be generic and overloaded, and generics are further enhanced by Nim's support for type classes. Operator overloading is also supported.[11] Nim includes multiple tunable memory management strategies, including tracing garbage collection, reference counting, and fully manual systems, with the default being deterministic reference counting with optimizations via move semantics and cycle collection via trial deletion.[13]

> [Nim] ... presents a most original design that straddles Pascal and Python and compiles to C code or JavaScript.[14]

(As of August 2023), Nim compiles to C, C++, JavaScript, Objective-C,[15] and LLVM.[16]

## History

Branch  | Version  | Release date[17]

|
|

0.x  | 0.10.2  | 2014-12-29
0.11.2  | 2015-05-04
0.12.0  | 2015-10-27
0.13.0  | 2016-01-18
0.14.2  | 2016-06-09
0.15.2  | 2016-10-23
0.16.0  | 2017-01-08
0.17.2  | 2017-09-07
0.18.0  | 2018-03-01
0.19.6  | 2019-05-13
0.20.2  | 2019-06-17
1.0  | 1.0.0  | 2019-09-23
1.0.10  | 2020-10-27
1.2  | 1.2.0  | 2020-04-03
1.2.18  | 2022-02-09
1.4  | 1.4.0  | 2020-10-16
1.4.8  | 2021-05-25
1.6  | 1.6.0  | 2021-10-19
1.6.18  | 2023-12-19
2.0  | 2.0.0  | 2023-08-01
2.0.2  | 2023-12-19
{{{2}}}
For each 0.x branch, only the latest point release is listed.
For later branches, the first and the latest point release is listed.

Nim's initial development was started in 2005 by Andreas Rumpf. It was originally named Nimrod when the project was made public in 2008.[18]:4–11

The first version of the Nim compiler was written in Pascal using the Free Pascal compiler.[19] In 2008, a version of the compiler written in Nim was released.[20] The compiler is free and open-source software, and is being developed by a community of volunteers working with Andreas Rumpf.[21] The language was officially renamed from Nimrod to Nim with the release of version 0.10.2 in December 2014.[22] On September 23, 2019, version 1.0 of Nim was released, signifying the maturing of the language and its toolchain. On August 1st, 2023, version 2.0 of Nim was released, signifying the completion, stabilization of, and switch to the ARC/ORC memory model.[23]

## Language design

### Syntax

The syntax of Nim resembles that of Python.[24] Code blocks and nesting statements are identified through use of whitespace, according to the offside-rule. Many keywords are identical to their Python equivalents, which are mostly English keywords, whereas other programming languages usually use punctuation. With the goal of improving upon its influence languages, even though Nim supports indentation-based syntax like Python, it introduced additional flexibility. For example, a single statement may span multiple lines if a comma or binary operator is at the end of each line. Nim also supports user-defined operators.

Unlike Python, Nim implements (native) static typing. Nim's type system allows for easy type conversion, casting, and provides syntax for generic programming. Nim notably provides type classes which can stand in for multiple types, and provides several such type classes 'out of the box'. Type classes allow working with several types as if they were a single type. For example:

* `openarray` – Represents arrays of different sizes, sequences, and strings
* `SomeSignedInt` – Represents all the signed integer types
* `SomeInteger` – Represents all the Integer types, signed or not
* `SomeOrdinal` – Represents all the basic countable and ordered types, except of non integer number

This code sample demonstrates the use of typeclasses in Nim

# 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)

### Influence

According to the language creator, Nim was conceived to combine the best parts of Ada typing system, Python flexibility, and powerful Lisp macro system.[25]

Nim was influenced by specific characteristics of existing languages, including the following:

* Modula-3: traced vs untraced pointers
* Object Pascal: type safe bit sets (set of char), case statement syntax, various type names and filenames in the standard library
* Ada: subrange types, distinct type, safe variants – case objects
* C++: operator overloading, generic programming
* Python: Off-side rule
* Lisp: Macro system, AST manipulation, homoiconicity
* Oberon: export marker
* C#: async/await, lambda macros
* ParaSail: pointer-free programming[6]

### Uniform Function Call Syntax

Nim supports Uniform Function Call Syntax (UFCS)[26] and identifier equality, which provides a large degree of flexibility in use.

For example, each of these lines print "hello world", just with different syntax:

echo "hello world"
echo("hello world")
"hello world".echo()
"hello world".echo
echo("hello", " world")
"hello".echo(" world")
"hello".echo " world"

### Identifier equality

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.[27]

const useHttps = true
assert useHttps == useHttps
assert useHTTPS == useHttps
assert use_https == useHttps

### Stropping

The stropping feature allows the use of any name for variables or functions, even when the names are reserved words for keywords. An example of stropping is the ability to define a variable named `if`, without clashing with the keyword `if`. Nim's implementation of this is achieved via backticks, allowing any reserved word to be used as an identifier.[28]

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`

## Compiler

The Nim compiler emits fast, optimized C code by default. It defers compiling-to-object code to an external C compiler[29] to leverage existing compiler optimization and portability. Many C compilers are supported, including Clang, Microsoft Visual C++ (MSVC), MinGW, and GNU Compiler Collection (GCC). The Nim compiler can also emit C++, Objective-C, and JavaScript code to allow easy interfacing with application programming interfaces (APIs) written in those languages;[7] developers can simply write in Nim, then compile to any supported language. This also allows writing applications for iOS and Android. There is also an unofficial LLVM backend, allowing use of the Nim compiler in a stand-alone way.[16]

The Nim compiler is self-hosting, meaning it is written in the Nim language.[30] The compiler supports cross-compiling, so it is able to compile software for any of the supported operating systems, no matter the development machine. This is useful for compiling applications for embedded systems, and for uncommon and obscure computer architectures.[citation needed]

### Compiler options

By default, the Nim compiler creates a debug build.[31] With the option `-d:release` a release build can be created, which is optimized for speed and contains fewer runtime checks.[31] With the option `-d:danger` all runtime checks can be disabled, if maximum speed is desired.[31]

### Memory management

Nim supports multiple memory management strategies, including the following:[32]

* `--gc:refc` – Standard deferred reference counting based garbage collector with a simple mark-and-sweep backup GC in order to collect cycles. Heaps are thread-local.
* `--gc:markAndSweep` – Simple mark-and-sweep based garbage collector. Heaps are thread-local.
* `--gc:boehm` – Boehm based garbage collector, it offers a shared heap.
* `--gc:go` – Go's garbage collector, useful for interoperability with Go. Offers a shared heap.
* `--gc:arc` – Automatic reference counting (ARC) with move semantics optimizations, offers a shared heap. It offers fully deterministic performance for hard realtime systems.[33] Reference cycles may cause memory leaks: these may be dealt with by manually annotating `{.acyclic.}` pragmas or by using `--gc:orc`.
* `--gc:orc` – Same as `--gc:arc` but adds a cycle collector (the "O") based on "trial deletion".[34] The cycle collector only analyzes types if they are potentially cyclic.
* `--gc:none` – No memory management strategy nor a garbage collector. Allocated memory is simply never freed, unless manually freed by the developer's code.

As of Nim 2.0, ORC is the default GC.[35]

## Development tools

### Bundled

Many tools are bundled with the Nim install package, including:

#### Nimble

Nimble is the standard package manager used by Nim to package Nim modules.[36] It was initially developed by Dominik Picheta, who is also a core Nim developer. Nimble has been included as Nim's official package manager since Oct 27, 2015, the v0.12.0 release.[37]

Nimble packages are defined by `.nimble` files, which contain information about the package version, author, license, description, dependencies, and more.[18]:132 These files support a limited subset of the Nim syntax called NimScript, with the main limitation being the access to the FFI. These scripts allow changing of test procedure, or for custom tasks to be written.

The list of packages is stored in a JavaScript Object Notation (JSON) file which is freely accessible in the nim-lang/packages repository on GitHub. This JSON file provides Nimble with a mapping between the names of packages and their Git or Mercurial repository URLs.

Nimble comes with the Nim compiler. Thus, it is possible to test the Nimble environment by running: `nimble -v`. This command will reveal the version number, compiling date and time, and Git hash of nimble. Nimble uses the Git package, which must be available for Nimble to function properly. The Nimble command-line is used as an interface for installing, removing (uninstalling), and upgrading–patching module packages.[18]:130–131

#### c2nim

c2nim is a source-to-source compiler (transcompiler or transpiler) meant to be used on C/C++ headers to help generate new Nim bindings.[38] The output is human-readable Nim code that is meant to be edited by hand after the translation process.

#### koch

koch is a maintenance script that is used to build Nim, and provide HTML documentation.[39]

#### nimgrep

nimgrep is a generic tool for manipulating text. It is used to search for regex, peg patterns, and contents of directories, and it can be used to replace tasks. It is included to assist with searching Nim's style-insensitive identifiers.[40]

#### nimsuggest

nimsuggest is a tool that helps any source code editor query a `.nim` source file to obtain useful information like definition of symbols or suggestions for completions.[41]

#### niminst

niminst is a tool to generate an installer for a Nim program.[42] It creates .msi installers for Windows via Inno Setup, and install and uninstall scripts for Linux, macOS, and Berkeley Software Distribution (BSD).

#### nimpretty

nimpretty is a source code beautifier, used to format code according to the official Nim style guide.[43]

#### Testament

Testament is an advanced automatic unit tests runner for Nim tests. Used in developing Nim, it offers process isolation tests, generates statistics about test cases, supports multiple targets and simulated Dry-Runs, has logging, can generate HTML reports, can skip tests from a file, and more.

### Other notable tools

Some notable tools not included in the Nim distribution include:

#### choosenim

choosenim was developed by Dominik Picheta, creator of the Nimble package manager, as a tool to enable installing and using multiple versions of the Nim compiler. It downloads any Nim stable or development compiler version from the command line, enabling easy switching between them.[44]

#### nimpy

nimpy is a library that enables convenient Python integration in Nim programs.[45]

#### pixie

pixie is a feature-rich 2D graphics library, similar to Cairo or the Skia. It uses SIMD acceleration to speed-up image manipulation drastically. It supports many image formats, blending, masking, blurring, and can be combined with the boxy library to do hardware accelerated rendering.

#### nimterop

nimterop is a tool focused on automating the creation of C/C++ wrappers needed for Nim's foreign function interface.[46]

## Libraries

### Pure/impure libraries

Pure libraries are modules written in Nim only. They include no wrappers to access libraries written in other programming languages.

Impure libraries are modules of Nim code which depend on external libraries that are written in other programming languages such as C.

### Standard library

The Nim standard library includes modules for all basic tasks, including:[47]

* System and core modules
* Collections and algorithms
* String handling
* Time handling
* Generic Operating System Services
* Math libraries
* Internet Protocols and Support
* Threading
* Parsers
* Docutils
* XML Processing
* XML and HTML code generator
* Hashing
* Database support (PostgreSQL, MySQL and SQLite)
* Wrappers (Win32 API, POSIX)

### Use of other libraries

A Nim program can use any library which can be used in a C, C++, or JavaScript program. Language bindings exist for many libraries, including GTK,[48][49] Qt QML,[50] wxWidgets,[51] SDL 2,[52][53] Cairo,[54] OpenGL,[55] WinAPI,[56] zlib, libzip, OpenSSL, Vulkan[57] and cURL.[58] Nim works with PostgreSQL, MySQL, and SQLite databases.

There are open source tools of various degree of support that can be used to interface Nim with Lua,[59] Julia,[60] Rust,[61] C#,[62] and Python[63] programming languages or transpile Nim to TypeScript.[64]

## Examples

### Hello world

The "Hello, World!" program in Nim:

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")

### Fibonacci

Several implementations of the Fibonacci function, showcasing implicit returns, default parameters, iterators, recursion, and while loops:

proc fib(n: Natural): Natural =
if n < 2:
return n
else:
return fib(n-1) + fib(n-2)

func fib2(n: int, a = 0, b = 1): int =
if n == 0: a else: fib2(n-1, b, a+b)

iterator fib3: int =
var a = 0
var b = 1
while true:
yield a
swap a, b
b += a

### Factorial

Program to calculate the factorial of a positive integer using the iterative approach, showcasing try/catch error handling and for loops:

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)

### Reversing a string

A simple demonstration showing the implicit result variable and the use of iterators.

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.

### Graphical user interface

Using GTK 3 with GObject introspection through the gintro module:

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

### Functional programming

Functional programming is supported in Nim through first-class functions and code without side effects via the `noSideEffect` pragma or the `func` keyword.[65] Nim will perform side effect analysis and raise compilation errors for code that does not obey the contract of producing no side effects when compiled with the experimental feature `strictFuncs`, planned to become the default in later versions.[66]

Contrary to purely functional programming languages, Nim is a multi-paradigm programming language, so functional programming restrictions are opt-in on a function-by-function basis.

#### First-class functions

Nim supports first-class functions by allowing functions to be stored in variables or passed anonymously as parameters to be invoked by other functions.[67] The `std/sugar` module provides syntactic sugar for anonymous functions in type declarations and instantiation.

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 ..< s.len:
if pred(s[i]):
result.add(s[i])

echo powersOfTwo.filter(proc (x: int): bool = x > 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)

#### Side effects

Side effects of functions annotated with the `noSideEffect` pragma are checked, and the compiler will refuse to compile functions failing to meet those. Side effects in Nim include mutation, global state access or modification, asynchronous code, threaded code, and IO. Mutation of parameters may occur for functions taking parameters of `var` or `ref` type: this is expected to fail to compile with the currently-experimental `strictFuncs` in the future.[68] The `func` keyword introduces a shortcut for a `noSideEffect` pragma.[69]

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

#### Function composition

Uniform function call syntax allows for the chaining of arbitrary functions, perhaps best exemplified with the `std/sequtils` library.[70]

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

#### Algebraic data types and pattern matching

Nim has support for product types via the `object` type, and for sum types via object variants: raw representations of tagged unions, with an enumerated type tag that must be safely matched upon before fields of variants can be accessed.[71] These types can be composed algebraically. Structural pattern matching is available, but regulated to macros in various third-party libraries.[72]

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!")

### Object-oriented programming

Despite being primarily an imperative and functional language, Nim supports various features for enabling object-oriented paradigms.[73][74]

#### Subtyping and inheritance

Nim supports limited inheritance by use of `ref objects` and the `of` keyword.[74] To enable inheritance, any initial ("root") object must inherit from `RootObj`. Inheritance is of limited use within idiomatic Nim code: with the notable exception of Exceptions.[75]

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.[74]

#### Method calls and encapsulation

Nim's uniform function call syntax enables calling ordinary functions with syntax similar to method call invocations in other programming languages. This is functional for "getters": and Nim also provides syntax for the creation of such "setters" as well. Objects may be made public on a per-field basis, providing for encapsulation.

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)

#### Dynamic dispatch

Static dispatch is preferred, more performant, and standard even among method-looking routines.[74] Nonetheless, if dynamic dispatch is so desired, Nim provides the `method` keyword for enabling dynamic dispatch on reference types.

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()

### Metaprogramming

#### Templates

Nim supports simple substitution on the abstract syntax tree via its templates.

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.

#### Generics

Nim supports both constrained and unconstrained generic programming. Generics may be used in procedures, templates and macros. Unconstrained generic identifiers (`T` in this example) are defined after the routine's name in square brackets. Constrained generics can be placed on generic identifiers, or directly on parameters.

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`).[76]

#### Macros

Macros can rewrite parts of the code at compile-time. Nim macros are powerful and can operate on the abstract syntax tree before or after semantic checking.[77]

Here's a simple example that creates a macro to call code twice:

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!"

### Foreign function interface (FFI)

Nim's FFI is used to call functions written in the other programming languages that it can compile to. This means that libraries written in C, C++, Objective-C, and JavaScript can be used in the Nim source code. One should be aware that both JavaScript and C, C++, or Objective-C libraries cannot be combined in the same program, as they are not as compatible with JavaScript as they are with each other. Both C++ and Objective-C are based on and compatible with C, but JavaScript is incompatible, as a dynamic, client-side web-based language.[18]:226

The following program shows the ease with which external C code can be used directly in Nim.

proc printf(formatstr: cstring) {.header: "<stdio.h>", 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 compilation 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.

### Parallelism

To activate threading support in Nim, a program should be compiled with `--threads:on` command line argument. Each thread has a separate garbage collected heap and sharing of memory is restricted, which helps with efficiency and stops race conditions by the threads.

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())

### Concurrency

Asynchronous IO is supported either via the `asyncdispatch` module in the standard library or the external `chronos` library.[78] Both libraries add async/await syntax via the macro system, without need for special language support. An example of an asynchronous HTTP server:

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)

## Community

### Online

Nim has an active community on the self-hosted, self-developed official forum.[79] Further, the project uses a Git repository, bug tracker, RFC tracker, and wiki hosted by GitHub, where the community engages with the language.[80] There are also official online chat rooms, bridged between IRC, Matrix, Discord, Gitter, and Telegram.[81]

### Conventions

The first Nim conference, NimConf, took place on June 20, 2020. It was held digitally due to COVID-19, with an open call for contributor talks in the form of YouTube videos.[82] The conference began with language overviews by Nim developers Andreas Rumpf and Dominik Picheta. Presentation topics included talks about web frameworks, mobile development, Internet of things (IoT) devices, and game development, including a talk about writing Nim for Game Boy Advance.[83] NimConf 2020 is available as a YouTube playlist.[84] NimConf 2021 occurred the following year, was also held digitally, and included talks about game development, REPLs, real-time operating systems, Nim in the industry, object-relational mapping (ORM), language design, and graphics libraries.[85]

In addition to official conferences, Nim has been featured at various other conventions. A presentation on Nim was given at the O'Reilly Open Source Convention (OSCON) in 2015.[86][87][88] Four speakers represented Nim at FOSDEM 2020, including the creator of the language, Andreas Rumpf.[89] At FOSDEM 2022, Nim hosted their own developer room virtually due to the COVID-19 pandemic.[90] Talks were held on concurrency, embedded programming, programming for GPUs, entity-component systems, game development, rules engines, Python interop, and metaprogramming.[91]

## See also

* C (programming language)
* C++ (programming language)
* Crystal (programming language)
* D (programming language)
* Go (programming language)
* Rust (programming language)
* Fat pointer

## References

1. ↑ "Contributors to nim-lang/Nim". https://github.com/nim-lang/Nim/graphs/contributors.
2. ↑ "Nim by example". https://nim-by-example.github.io/.
3. ↑ Караджов, Захари; Станимиров, Борислав (2014). "Метапрограмиране с Nimrod" (in bg). VarnaConf. https://ibob.github.io/slides/nimrodbg/#/. Retrieved 2014-07-27.
4. ↑ "Packaging Nim". https://nim-lang.org/docs/packaging.html.
5. ↑ "Install Nim". https://nim-lang.org/install.html.
6. ↑ 6.0 6.1 Rumpf, Andreas (2017-10-19). "Nim without GC". https://nim-lang.org/araq/destructors.html.
7. ↑ 7.0 7.1 Rumpf, Andreas (2014-02-11). "Nimrod: A new systems programming language". http://www.drdobbs.com/open-source/nimrod-a-new-systems-programming-languag/240165321.
8. ↑ "The Nim Programming Language". http://nim-lang.org/.
9. ↑ "FAQ". https://nim-lang.org/faq.html.
10. ↑ Kehrer, Aaron (akehrer) (5 January 2015). "Nim Syntax". https://akehrer.github.io/posts/getting-started-with-nim.
11. ↑ 11.0 11.1 11.2 "Nim Manual". https://nim-lang.org/docs/manual.html#term-rewriting-macros.
12. ↑ "Strangeloop Nim presentation". https://thestrangeloop.com/sessions/nimrod-a-new-approach-to-meta-programming.
13. ↑ "Nim's Memory Management". https://nim-lang.org/docs/mm.html.
14. ↑ Binstock, Andrew (2014-01-07). "The Rise And Fall of Languages in 2013". http://www.drdobbs.com/jvm/the-rise-and-fall-of-languages-in-2013/240165192.
15. ↑ Nim Compiler User Guide
16. ↑ 16.0 16.1 Sieka, Jacek (2020-07-18), arnetheduck/nlvm, https://github.com/arnetheduck/nlvm, retrieved 2020-07-21
17. ↑ "Nim Releases". Nim Project. https://github.com/nim-lang/Nim/releases.
18. ↑ 18.0 18.1 18.2 18.3 Picheta, Dominik (2017). Nim in Action. Manning Publications. ISBN 978-1617293436.
19. ↑ "Nim Pascal Sources". https://github.com/Araq/Nim/tree/ea1f1ec6d4d6c776eb0f81c2bebdd4cb4c817ebe/nim.
20. ↑ "News". http://nim-lang.org:80/news.html.
21. ↑ "Contributors". https://github.com/Araq/Nim/contributors.
22. ↑ Picheta, Dominik (2014-12-29). "Version 0.10.2 released". https://nim-lang.org/blog/2014/12/29/version-0102-released.html.
23. ↑ "Nim v2.0 released" (in en). https://nim-lang.org/blog/2023/08/01/nim-v20-released.html.
24. ↑ Yegulalp, Serdar (2017-01-16). "Nim language draws from best of Python, Rust, Go, and Lisp". https://www.infoworld.com/article/3157745/application-development/nim-language-draws-from-best-of-python-rust-go-and-lisp.html.
25. ↑ (in en) Interview with Nim language creator Andreas Rumpf, https://www.youtube.com/watch?v=-9SGIB946lw, retrieved 2023-10-15
26. ↑ "Nim Manual: Method call syntax". http://nim-lang.org/docs/manual.html#procedures-method-call-syntax.
27. ↑ "Nim Manual: Identifier Equality". https://nim-lang.org/docs/manual.html#lexical-analysis-identifier-equality.
28. ↑ Picheta, Dominik (dom96); Wetherfordshire, Billingsly (fowlmouth); Felsing, Dennis (def-); Raaf, Hans (oderwat); Dunn, Christopher (cdunn2001) (2017-10-25). "Tips and tricks". https://github.com/nim-lang/Nim/wiki/Tips-and-tricks.
29. ↑ Rumpf, Andreas (2014-01-15). Nimrod: A New Approach to Metaprogramming. InfoQ. Event occurs at 2:23. Retrieved 2014-07-20.
30. ↑ Rumpf, Andreas (2018-10-12). "Nim Compiling". https://github.com/nim-lang/Nim#compiling.
31. ↑ 31.0 31.1 31.2 "Nim Compiler User Guide". https://nim-lang.org/docs/nimc.html#compiler-usage-configuration-files.
32. ↑ "Nim's Memory Management". https://nim-lang.org/docs/mm.html.
33. ↑ "Introduction to ARC/ORC in Nim" (in en). https://nim-lang.org/blog/2020/10/15/introduction-to-arc-orc-in-nim.html.
34. ↑ "ORC - Vorsprung durch Algorithmen" (in en). https://nim-lang.org/blog/2020/12/08/introducing-orc.html.
35. ↑ "Nim v2.0 released" (in en). https://nim-lang.org/blog/2023/08/01/nim-v20-released.html.
36. ↑ "Nimble". https://github.com/nim-lang/nimble.
37. ↑ "Nim v0.12.0 release". https://github.com/nim-lang/Nim/commit/49d810f3410c19803f2d6fbfb3feb03e1fc13fee.
38. ↑ "c2nim". https://github.com/nim-lang/c2nim.
39. ↑ "Nim maintenance script". https://nim-lang.org/docs/koch.html.
40. ↑ "nimgrep User's manual". https://nim-lang.org/docs/nimgrep.html.
41. ↑ "Nim IDE Integration Guide". https://nim-lang.org/docs/nimsuggest.html.
42. ↑ "niminst User's manual". https://nim-lang.org/docs/niminst.html.
43. ↑ "Tools available with Nim". 2021-10-19. https://nim-lang.org/docs/tools.html.
44. ↑ "choosenim". https://github.com/dom96/choosenim.
45. ↑ Glukhov, Yuriy (2021-11-12), nimpy, https://github.com/yglukhov/nimpy, retrieved 2021-11-16
46. ↑ nimterop/nimterop, nimterop, 2021-11-12, https://github.com/nimterop/nimterop, retrieved 2021-11-16
47. ↑ Nim Standard Library
48. ↑ Installation, The Nim programming language, 2021-09-25, https://github.com/nim-lang/gtk2, retrieved 2021-11-16
49. ↑ StefanSalewski (2021-11-15), High level GTK4 and GTK3 bindings for the Nim programming language, https://github.com/StefanSalewski/gintro, retrieved 2021-11-16
50. ↑ "NimQml". 10 November 2022. https://github.com/status-im/NimQml.
51. ↑ "WxNim". 29 November 2022. https://github.com/PMunch/wxnim.
52. ↑ SDL2 for Nim, The Nim programming language, 2021-10-26, https://github.com/nim-lang/sdl2, retrieved 2021-11-16
53. ↑ Arabadzhi, Vladimir (2021-11-15), sdl2_nim 2.0.14.2, https://github.com/Vladar4/sdl2_nim, retrieved 2021-11-16
54. ↑ Cairo, The Nim programming language, 2021-10-05, https://github.com/nim-lang/cairo, retrieved 2021-11-16
55. ↑ opengl, The Nim programming language, 2021-11-14, https://github.com/nim-lang/opengl, retrieved 2021-11-16
56. ↑ Ward (2021-11-15), Winim, https://github.com/khchen/winim, retrieved 2021-11-16
57. ↑ "Vulkanim". 30 September 2022. https://github.com/Clyybber/vulkanim.
58. ↑ "Nim Standard Library". http://nim-lang.org/lib.html.
59. ↑ Lim, Andri (jangko) (2018-10-17). "nimLUA". https://github.com/jangko/nimLUA.
60. ↑ "NimJL". 24 August 2022. https://github.com/Clonkk/nimjl.
61. ↑ "Nbindgen". 17 November 2022. https://github.com/arnetheduck/nbindgen.
62. ↑ "cs2nim". 10 October 2022. https://github.com/kobi2187/cs2nim.
63. ↑ Glukhov, Yuriy (2020-07-20), yglukhov/nimpy, https://github.com/yglukhov/nimpy, retrieved 2020-07-21
64. ↑ "ts2nim". 21 November 2022. https://github.com/bung87/ts2nim.
65. ↑ "Nim Manual". https://nim-lang.org/docs/manual.html#procedures-func.
66. ↑ "Nim Forum: Update on strict funcs". https://forum.nim-lang.org/t/9716.
67. ↑ "Nim by Example - First Class Functions". https://nim-by-example.github.io/procvars/.
68. ↑ "Nim Experimental Features: Strict Funcs". https://nim-lang.org/docs/manual_experimental.html#strict-funcs.
69. ↑ "Nim Manual: Func". https://nim-lang.org/docs/manual.html#procedures-func.
70. ↑ "std/sequtils". https://nim-lang.org/docs/sequtils.html.
71. ↑ "Nim Manual: Object variants". https://nim-lang.org/docs/manual.html#types-object-variants.
72. ↑ "src/fusion/matching". https://nim-lang.github.io/fusion/src/fusion/matching.html.
73. ↑ "Nim Tutorial (Part II): Object Oriented Programming". https://nim-lang.org/docs/tut2.html#object-oriented-programming.
74. ↑ 74.0 74.1 74.2 74.3 "Nim by Example - Object Oriented Programming". https://nim-by-example.github.io/oop/.
75. ↑ "system/exceptions". https://nim-lang.org/docs/exceptions.html.
76. ↑ "Nim Manual: Type Classes". https://nim-lang.org/docs/manual.html#generics-type-classes.
77. ↑ "Nim Tutorial (Part III)". https://nim-lang.org/docs/tut3.html.
78. ↑ Chronos - An efficient library for asynchronous programming, Status, 2023-08-14, https://github.com/status-im/nim-chronos, retrieved 2023-08-17
79. ↑ "Nim Forum". nim-lang.org. http://forum.nim-lang.org.
80. ↑ "Primary source code repository and bug tracker". https://github.com/Araq/Nim.
81. ↑ "Community" (in en). https://nim-lang.org/community.html.
82. ↑ "Nim Online Conference 2020". https://nim-lang.org/blog/2020/05/14/nim-conference.html.
83. ↑ "NimConf 2020". https://conf.nim-lang.org/2020/.
84. ↑ "NimConf 2020 Playlist". https://www.youtube.com/playlist?list=PLxLdEZg8DRwTIEzUpfaIcBqhsj09mLWHx.
85. ↑ "NimConf 2021" (in en). https://conf.nim-lang.org/.
86. ↑ "Nim at OSCON 2015". O'Reilly Media. 2015-07-20. http://www.oscon.com/open-source-2015/public/schedule/detail/42497.
87. ↑ Rumpf, Andreas; Swartz, Jason; Harrison, Matt. "Essential Languages: Nim, Scala, Python". O'Reilly Media. http://www.oreilly.com/pub/e/3420.
88. ↑ Rumpf, Andreas (2015-10-26). OSCON 2015 – Nim: An Overview. YouTube (Video). Retrieved 2018-10-12.
89. ↑ "Events" (in en). https://fosdem.org/2020/schedule/events/.
90. ↑ "Nim Devroom at FOSDEM 2022 - Call for Participation" (in en). https://nim-lang.org/blog/2021/12/02/fosdem-2022-cfp.html.
91. ↑ "Nim Programming Language devroom" (in en). https://archive.fosdem.org/2022/schedule/track/nim_programming_language/.

## External links

* on GitHub
* Information about Nim on Stack Overflow
* Computer Programming with the Nim Programming Language A gentle Introduction by Stefan Salewski

* v
* t
* e

Programming languages

* Comparison
* Timeline
* History

* APL
* Assembly
* BASIC
* C
* C++
* C#
* COBOL
* Elixir
* Fortran
* Go
* Groovy
* Haskell
* Java
* JavaScript (JS)
* Julia
* Kotlin
* Lisp
* Lua
* MATLAB
* Objective-C
* OCaml
* Pascal
* Perl
* PHP
* Python
* R
* Ruby
* Rust
* Scala
* Shell
* Smalltalk
* Swift
* TypeScript
* Visual Basic .NET (VB.NET)
* more...

* Category
* Lists
* Alphabetical
* Categorical
* Generational
* Non-English-based

* v
* t
* e

JavaScript

Code analysis|

* ESLint
* JSHint
* JSLint

Transcompilers|

* Babel.js
* CoffeeScript
* LiveScript
* Dart
* Emscripten
* Google Closure Compiler
* Google Web Toolkit
* Morfik
* TypeScript
* AtScript
* Opa
* Nim
* Haxe
* ClojureScript
* WebSharper
* PureScript
* Reason
* Elm

Concepts|

* Client-side
* JavaScript library
* JavaScript syntax
* Unobtrusive JavaScript

Debuggers|

* Firebug
* Komodo IDE
* Microsoft Script Debugger
* Microsoft Script Editor
* Opera Dragonfly
* Web Inspector

Doc generators|

* JSDoc

Editors (comparison)|

* Ace
* Cloud9 IDE
* Atom
* CodeMirror
* Light Table
* Brackets
* Koding
* PhpStorm
* Orion
* Visual Studio
* Visual Studio Express
* Visual Studio Code
* Visual Studio Team Services

Engines|

* Comparison of engines
* DOM support
* List of ECMAScript engines

Frameworks|

* Comparison of JavaScript frameworks
* List of JavaScript libraries

Related technologies|

* Cascading Style Sheets
* Document Object Model
* HTML
* Dynamic HTML
* Ajax
* JSON
* WebAssembly
* asm.js

Package managers|

* npm

Application Bundlers|

* Webpack

Server-side|

* Active Server Pages
* CommonJS
* JSGI
* Node.js
* Wakanda

Unit testing|

* Jasmine
* Mocha
* QUnit
* List of JavaScript unit testing frameworks
* Jest

People|

* Douglas Crockford
* Brendan Eich
* John Resig

0.00

(0 votes)

Original source: https://en.wikipedia.org/wiki/Nim (programming language). Read more

|

Retrieved from "https://handwiki.org/wiki/index.php?title=Nim_(programming_language)&oldid=3382874"
*[v]: View this template
*[t]: Discuss this template
*[e]: Edit this template