Skip to content

Instantly share code, notes, and snippets.

@diegopacheco
Last active March 4, 2024 08:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diegopacheco/0fb84d881e2423147d9cb6f8619bf473 to your computer and use it in GitHub Desktop.
Save diegopacheco/0fb84d881e2423147d9cb6f8619bf473 to your computer and use it in GitHub Desktop.
Having fun with Nim Lang

Tiny Nim Essay

created: 24.MAR.2023

I love to learn new programing languages, it help to open the mind to new possibilities and compare different approaches. For instance, I learned Ruby and Scala in 2010, Clojure and Haskell in 2011, Go in 2015, Kotlin 2016, Rust in 2018 and Idris, TypeScript in 2019, 2020 Pandemic strike did a bunch of pocs but not with new langs(crazy year), Zig in 2021, 2022(coding in lots of langs but nothing new) - in 2023 I'm learning Nim and V. Learn at least one lang per year. This post is not complain, it's just to share some toughts, notes and impressions.

Why Nim

My Feelings (24.MAR.2023 Nim-lang version 1.6.10)

  • Fast compilation
  • Fun to code with
  • Unit tests, json built-in
  • No complex types, very simple constructs, but can get complex with macros, oop.
  • Dolcumentation is too basic, far from ideal. Not widely adopted in the industry.
  • As fast as C, expressive as python, but less confusing them python
  • OOP is a bit verbose (like rust and go)
  • make the function(procedure) public requires "*" not obvious.
  • Feels like a better Python

Show me the code

My POCs with Nim: https://github.com/diegopacheco/nim-playground

1 - Nice Slicing like Go

let abc = ['a', 'b', 'c', 'd', 'e']
echo fmt"first {abc[0]}"
echo fmt"last {abc[^1]}"
echo fmt"slice {abc[1..3]}"

2 - For Loops like Go

let word2 = "cool"
for i, c in word2:
    echo fmt"{i} index char is: {c}"

3 - Implicit Result var

proc getAlphabet(): string =
  for letter in 'a'..'z':
    result.add(letter)

4 - Json support

import json

type
  Element = object
    name: string
    atomicNumber: int

let jsonObject = parseJson("""{"name": "Carbon", "atomicNumber": 6}""")
let element = to(jsonObject, Element)
echo element.name
echo element.atomicNumber

5 - Channels

import os
import threadpool

var ch: Channel[string]
ch.open()

proc orderDish() =
  sleep(1000)
  ch.send("[French Fries]")

proc reciveKitchen() =
  let msg = ch.recv()
  echo "Received dish - working on it: " & msg

spawn orderDish()
spawn reciveKitchen()
sync()

Other Tiny Essays

About me

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment