For Python Programmers

Ever wondered if there existed a language

  • as fast as C

  • as expressive as Python

  • as extensible as Lisp

Look no further then!

Abhishek

Engineer @ Netflix

 

Twitter/Github: @cabhishek

San Francisco

Talk intent

  • Quick Intro
  • Python vs Nim
  • Why Nim?
  • Nim resources

What is Nim?

Nim is an incredibly fast systems and applications programming language that is expressive, extensible and fun to use.

  echo "hello, 世界"

Who develops Nim?

  • 400+ Committers
  • 3000+ PR's merged
  • 4000+ Issues fixed
  • 700+ Packages
  • 14,000+ Commits

Volunteers

  • Actively developed ~2008 
  • MIT License
  • Created by Andreas Rumpf

Language goals

  1. Efficiency

  2. Expressiveness

  3. Elegance

Python vs Nim

A Map of the Territory

Nim Code

Nim compiler

 

C code

C compiler

Executable

Features Python Nim
Memory Management Automatic Automatic or Manual
Types Dynamic Static
Generics Duck Typing Yes
Object Oriented Yes Minimal
Closures Yes Yes
Function overload No Yes
Distribution Requires CPython Binary
Multi Threaded No Yes
Performance Depends? similar to C/C++

Why Nim?

Efficient

Expressive

Metaprogramming

Cross Platform

Expressive

Clean syntax

  • Allows users to write easy-to-read high-performance code
proc search(a: seq[int], key: int): bool =
  # type inferred
  var
    low = 0
    high = len(a) - 1

  while low <= high:
    let mid: int = (low + high) div 2 # integer division
    if key < a[mid]:
      high = mid - 1
    elif key > a[mid]:
      low = mid + 1
    else:
      return true

  return false

echo search(@[2,3,4,5,6,7,8], 5) # true

Universal function call syntax (UFCS)

  • UFCS allows  procedures to be called using the syntax for method calls, by using the receiver as the first parameter, and the given arguments as the remaining parameters
    • e.g It allows you to write a.square(b) or square(a, b) interchangeably
  • This feature is especially useful when chaining complex function calls

 

Instead of writing

 

foo(bar(a))
a.bar().foo()

It is possible to write

echo evens(divide(multiply(values, 10), 3))

vs

echo values.multiply(10).divide(3).evens

Intuitive type system

import strutils, strformat

type
    Person = object
        name: string
        age: int

proc speak (p: Person) =
    echo fmt"My name is {p.name} and I am {p.age} years old."

let person = Person(name: "jim", age: 30)

person.speak() # My name is jim and I am 30 years old.

Operator overloading

type Point = tuple[x, y: int]

proc `+`(a, b: Point): Point =
  (a.x + b.x, a.y + b.y)

let
  p1 = (x: -1, y: 4)
  p2 = (x: 5, y: -2)
  p3 = p1 + p2

echo p3 # (x: 4, y: 2)
  • Operators can have different implementations depending on their arguments
  • Operators are simply overloaded procedures

Metaprogramming

Metaprogramming is a feature of Nim that gives you the ability to treat your application’s source code as data. This means you can write code that reads, generates, analyses and modifies other code.

Templates

  • Allows simple substitution mechanism 

  • Simple way to reduce code duplication

  • To invoke a template, call it like a procedure

  • Templates are declarative

echo mul(2, 3)
echo 2 * 3

At compile time its re-written to

template mul(x, y: int): int = x * y

Macros

  • Enable advanced compile-time code transformations
  • Transform Nim syntax tree into a different tree
  • Reduce code boilerplate
  • Macros are procedural
import macros

macro mul(x, y: int): typed =
  expectKind(x, nnkIntLit)
  expectKind(y, nnkIntLit)

  let stmtList = newNimNode(nnkStmtList)
  stmtList.add(
    newCall(
      newIdentNode("echo"), 
      newStrLitNode("Result is: "),
      infix(x, "*", y)
    )      
  )
  return stmtList

mul(2, 2) # Result is: 4

Efficient

Cross platform

  • Supports C/C++ and Javascript backends

    • https://nim-lang.org/docs/backends.html

  • Cross compilation

    • https://nim-lang.org/docs/nimc.html#cross-compilation

  • Nim Installer

    • https://nim-lang.org/docs/niminst.html

Code samples

Other language features

  • Self hosted

  • No GIL

  • FFI (Foreign function interface)

  • async/await

  • Package manager

  • Docs generator

  • ....

Real-world​ use cases? 

  • Web services / API's

  • Command line applications

  • Compilers

  • Scientific computing

  • Games

  • Automation scripts

  • UI applications

  • Python C extensions 

  • And more...

Project showcase

  • Arraymancer: A fast, ergonomic and portable tensor library with a deep learning focus

  • ao: Physically based ray tracer in Nim

  • Jester: A sinatra-like web framework

  • Karax: Single page JS applications

  • Reel valley: Game in JS. Details here

  • Spry: Programing language

  • Nim pymod: Call Nim from Python

  • Razcal: Build cross platform desktop app with Lua, MoonScript, and Layout Language

  • NimLox: Interpreter for the 'Lox' language written in Nim

  • ...

Why not Nim?

  • Smaller ecosystem

  • Occasional compiler bugs

Links: How to get started

Summary

  • Language goals

    1. Efficiency

    2. Expressiveness

    3. Elegance 

  • Key takeaway points

    • Incredibly fast, extensible & fun

    • Python look & feel

    •  Zero dependency binary distribution

    • Comprehensive Std library

 

Thanks

Questions?

@cabhishek

[Short version] Nim for Python programmers

By Abhishek Kapatkar

[Short version] Nim for Python programmers

  • 1,170