Movatterモバイル変換


[0]ホーム

URL:


Efficient, expressive, elegant

Nim is a statically typed compiled systems programming language. It combines successful concepts from mature languages like Python, Ada and Modula.

Efficient

  • Nim generates native dependency-free executables, not dependent on a virtual machine, which are small and allow easy redistribution.
  • The Nim compiler and the generated executables support all major platforms like Windows, Linux, BSD and macOS.
  • Nim's memory management is deterministic and customizable with destructors and move semantics, inspired by C++ and Rust. It is well-suited for embedded, hard-realtime systems.
  • Modern concepts like zero-overhead iterators and compile-time evaluation of user-defined functions, in combination with the preference of value-based datatypes allocated on the stack, lead to extremely performant code.
  • Support for various backends: it compiles to C, C++ or JavaScript so that Nim can be used for all backend and frontend needs.

Expressive

  • Nim is self-contained: the compiler and the standard library are implemented in Nim.
  • Nim has a powerful macro system which allows direct manipulation of the AST, offering nearly unlimited opportunities.

Elegant

  • Macros cannot change Nim's syntax because there is no need for it — the syntax is flexible enough.
  • Modern type system with local type inference, tuples, generics and sum types.
  • Statements are grouped by indentation but can span multiple lines.
importstd/strformattypePerson=objectname:stringage:Natural# Ensures the age is positiveletpeople=[Person(name:"John",age:45),Person(name:"Kate",age:30)]forpersoninpeople:# Type-safe string interpolation,# evaluated at compile time.echo(fmt"{person.name} is {person.age} years old")# Thanks to Nim's 'iterator' and 'yield' constructs,# iterators are as easy to write as ordinary# functions. They are compiled to inline loops.iteratoroddNumbers[Idx,T](a:array[Idx,T]):T=forxina:ifxmod2==1:yieldxforoddinoddNumbers([3,6,9,12,15,18]):echoodd# Use Nim's macro system to transform a dense# data-centric description of x86 instructions# into lookup tables that are used by# assemblers and JITs.importmacros,strutilsmacrotoLookupTable(data:static[string]):untyped=result=newTree(nnkBracket)forwindata.split(';'):result.addnewLit(w)constdata="mov;btc;cli;xor"opcodes=toLookupTable(data)foroinopcodes:echoo
varconditional=42ifconditional<0:echo"conditional < 0"elifconditional>0:echo"conditional > 0"else:echo"conditional == 0"varternary=ifconditional==42:trueelse:falsevaranother=ifconditional==0:"zero"elifconditionalmod2==0:"even"else:"odd"# Case switch.varletter='c'caseletterof'a':echo"letter is 'a'"of'b','c':echo"letter is 'b' or 'c'"of'd'..'h':echo"letter is between 'd' and 'h'"else:echo"letter is another character"
importstd/math# Basic math.assert1+2==3# Sumassert4-1==3# Subtractionassert2*2==4# Multiplicationassert4/2==2.0# Divisionassert4div2==2# Integer Divisionassert2^3==8# Powerassert4mod2==0# Moduloassert(2xor4)==6# XORassert(4shr2)==1# Shift RightassertPI*2==TAU# PI and TAUassertsqrt(4.0)==2.0# Square Rootassertround(3.5)==4.0# RoundassertisPowerOfTwo(16)# Powers of Twoassertfloor(2.9)==2.0# Floorassertceil(2.9)==3.0# Ceilassertcos(TAU)==1.0# Cosineassertgcd(12,8)==4# Greatest common divisorasserttrunc(1.75)==1.0# TruncateassertfloorMod(8,3)==2# Floor ModuloassertfloorDiv(8,3)==2# Floor Divisionasserthypot(4.0,3.0)==5.0# Hypotenuseassertgamma(4.0)==6.0# Gamma functionassertradToDeg(TAU)==360.0# Radians to Degreesassertclamp(1.4,0.0..1.0)==1.0# ClampassertalmostEqual(PI,3.14159265358979)asserteuclDiv(-13,-3)==5# Euclidean DivisionasserteuclMod(-13,3)==2# Euclidean Modulo
importstd/[strutils,strscans]assert"con"&"cat"=="concat"assert"    a    ".strip=="a"assert"42".parseInt==42assert"3.14".parseFloat==3.14assert"0x666".parseHexInt==1638assert"TrUe".parseBool==trueassert"0o777".parseOctInt==511assert"a".repeat(9)=="aaaaaaaaa"assert"abc".startsWith("ab")assert"abc".endsWith("bc")assert["a","b","c"].join=="abc"assert"abcd".find("c")==2assert"a x a y a z".count("a")==3assert"A__B__C".normalize=="abc"assert"a,b".split(",")==@["a","b"]assert"a".center(5)=="  a  "assert"a".indent(4)=="    a"assert"    a".unindent(4)=="a"forwordintokenize("This is an example"):echowordlet(ok,year,month,day)=scanTuple("1000-01-01","$i-$i-$i")ifok:assertyear==1000assertmonth==1assertday==1
importstd/[sugar,tables,sets,sequtils,strutils]letvariable0=collect(newSeq):foritemin@[-9,1,42,0,-1,9]:item*2assertvariable0==@[-18,2,84,0,-2,18]letvariable1=collect(initTable):forkey,valuein@[0,5,9]:{key:valuediv2}assertvariable1=={0:0,1:2,2:4}.toTableletvariable2=collect(initHashSet):foritemin@[-9,1,42,0,-1,9]:{item+item}assertvariable2==[2,18,84,0,-18,-2].toHashSetasserttoSeq(1..15).mapIt(ifitmod15==0:"FizzBuzz"elifitmod5==0:"Buzz"elifitmod3==0:"Fizz"else:$it).join(" ").strip=="1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz"

Recent articles

05 February 2025

Nim version 2.2.2 released

The Nim Team is happy to announce version 2.2.2, the first patch release for our stable release, Nim 2.2.

23 January 2025

Nim Community Survey 2024 Results

Here are the results of Nim Community Survey 2024.
All articles

Mastering Nim

The definite guide on Nim!

Written by the inventor himself.

Now with updated content for version 2.0 which solves the biggest pain point of Nim 1.0, shared memory in a multi-threaded setting.

Buy it on amazon.comBuy it on amazon.de

Support Nim

Join the 100+ companies and individuals that support Nim

The Nim project is developed globally by a group of volunteers. We welcome recurring donations, which enable us to spend more time working on Nim.

Donate

Community

Real-time chat

#Libera.chat#nim

Discord/Nim

Gitter/Nim

m#nim:envs.net

#IRC Logs

Telegram/nim_lang

Forum

forum.nim-lang.org

r/nim

StackOverflow

Bug reports

nim-lang/Nim

Twitter

@nim_lang

Join the community

Looking for the GitHub repository?

The Nim compiler and tools are all written in Nim and licensed under the MIT license, with most development taking place on GitHub. Be sure to watch the repository to get updates on Nim's development, or star it to give us some brownie points.

Source code

[8]ページ先頭

©2009-2025 Movatter.jp