Nim Tutorial- Nim Programming Language

June 04, 2021


In this Tutorial, we are talking about Nim Programming language and also talk about the history of Nim, coding part is also covered and explains the advantages of  Nim Programming Language.

What is Nim Programming?

Nim is multi-paradigm, compiled programming language, and also statically typed programming language. It is also used object-oriented programming concepts like C, C++, Objective-C. It combines successful concepts from mature languages like Python. Nim is an imperative, general-purpose, multi-paradigm, statically typed, systems, compiled programming language.

How to Install Nim?

Go to the official website of Nim programming and install the latest version of Nim-

                           https://nim-lang.org/

History of Nim Programming -

The first development of Nim began in 2005. When the project was launched in 2008, it was originally named Nimrod. The first version of the Nim compiler was written in Pascal using the Free Pascal compiler. Developed by the volunteer community in collaboration with Andreas Rumpf. With the release of version 0.10.2 in December 2014, the language was officially renamed Nim from Nimrod. On September 23, 2019, Nim 1.0 version was released, which means that the language and its toolchain are mature. In 2008, a version of the compiler written in Nim was released. Nim was developed by Andreas Rumpf.

How to write Nim Programming syntax?

Let's take one example of "Hello World"

First, create a file with a name like helloworld.nim then save it with an extension of .nim, and inside this file write a little bit code for example write a code of -
                                    echo "Hello World!"
If we are writing this code using command then we are shown a command
  •     nim c helloworld.nim
  •    nim c -r helloworld.nim
   both commands are same you can choose anyone 

How to declare a variable?
The assignment needs to be declared before using the value because it is a statically typed programming language.


Let's take a one example of assign a variable without an explicit type like this:

 
Identifier equality - 
Nim programming language is case insensitive and it ignores underscores so let's take one example:
Stropping-
This means that any name can be used for a variable or function, even if the name is reserved for keywords. A similar tracking example is the ability to track a variable named yes, although it is not compatible with the yes keyword. This can be done with backticks, which allow any reserved word to be used as a character.



How to learn Nim only five minutes

We are given an example of some  data types 

#[
  This is a multiline comment.
  In Nim, multiline comments can be nested, beginning with #[
  ... and ending with ]#
]#
discard """
This can also work as a multiline comment.
Or for unparsable, broken code
"""
var                     

# Declare (and assign) variables,
  letter: char = 'n'    # with or without type annotations
  lang = "N" & "im"
  nLength: int = len(lang)
  boat: float
  truth: bool = false
let            # Use let to declare and bind variables *once*.
  legs = 400   # legs is immutable.
  arms = 2_000 # _ are ignored and are useful for long numbers.
  aboutPi = 3.15
const            # Constants are computed at compile time. This provides
  debug = true   # performance and is useful in compile time expressions.
  compileBadCode = false
when compileBadCode:            # `when` is a compile time `if`
  legs = legs + 1               # This error will never be compiled.
  const input = readline(stdin) # Const values must be known at compile time.
discard 1 > 2 # Note: The compiler will complain if the result of an expression
              # is unused. `discard` bypasses this.


# Data Structures

# Tuples
var
  child: tuple[name: string, age: int]   # Tuples have *both* field names
  today: tuple[sun: string, temp: float] # *and* order.
child = (name: "Rudiger", age: 2) # Assign all at once with literal ()
today.sun = "Overcast"            # or individual fields.
today.temp = 70.1
# Sequences
var
  drinks: seq[string]
drinks = @["Water", "Juice", "Chocolate"] # @[V1,..,Vn] is the sequence literal
drinks.add("Milk")
if "Milk" in drinks:
  echo "We have Milk and ", drinks.len - 1, " other drinks"
let myDrink = drinks[2]

# Defining Types
#
# Defining your own types puts the compiler to work for you. It's what makes
# static typing powerful and useful.
type
  Name = string # A type alias gives you a new type that is interchangeable
  Age = int     # with the old type but is more descriptive.
  Person = tuple[name: Name, age: Age] # Define data structures too.
  AnotherSyntax = tuple
    fieldOne: string
    secondField: int
var
  john: Person = (name: "John B.", age: 17)
  newage: int = 18 # It would be better to use Age than int
john.age = newage # But still works because int and Age are synonyms
type
  Cash = distinct int    # `distinct` makes a new type incompatible with its
  Desc = distinct string # base type.
var
  money: Cash = 100.Cash # `.Cash` converts the int to our type
  description: Desc  = "Interesting".Desc
when compile a code:
  john.age  = money        # Error! age is of type int and money is Cash
  john.name = description  # Compiler says: "No way!"

# More Types and Data Structures

# Enumerations allow a type to have one of a limited number of values
type
  Color = enum cRed, cBlue, cGreen
  Direction = enum # Alternative formatting
    dNorth
    dWest
    dEast
    dSouth
var
  orient = dNorth # `orient` is of type Direction, with the value `dNorth`
  pixel = cGreen # `pixel` is of type Color, with the value `cGreen`
discard dNorth > dEast # Enums are usually an "ordinal" type
# Subranges specify a limited valid range
type
  DieFaces = range[1..20] # Only an int from 1 to 20 is a valid value
var
  my_roll: DieFaces = 13
when compileBadCode:
  my_roll = 23 # Error!
explain Some other data types like Array etc
Arrays
type
  RollCounter = array[DieFaces, int]  # Array's are fixed length and
  DirNames = array[Direction, string] # indexed by any ordinal type.
  Truths = array[42..44, bool]
var
  counter: RollCounter
  directions: DirNames
  possible: Truths
possible = [false, false, false] # Literal arrays are created with [V1,..,Vn]
possible[42] = true
directions[dNorth] = "Ahh. The Great White North!"
directions[dWest] = "No, don't go there."
my_roll = 13
counter[my_roll] += 1
counter[my_roll] += 1
var anotherArray = ["Default index", "starts at", "0"]
# More data structures are available, including tables, sets, lists, queues,
# and crit bit trees.
# http://nim-lang.org/docs/lib.html#collections-and-algorithms
#
# IO and Control Flow
#
# `case`, `readLine()`
echo "Read any good books lately?"
case readLine(stdin)
of "no", "No":
  echo "Go to your local library."
of "yes", "Yes":
  echo "Carry on, then."
else:
  echo "That's great; I assume."
# `while`, `if`, `continue`, `break`
import strutils as str # http://nim-lang.org/docs/strutils.html
echo "I'm thinking of a number between 41 and 43. Guess which!"
let number: int = 42
var
  raw_guess: string
  guess: int
while guess != number:
  raw_guess = readLine(stdin)
  if raw_guess == "": continue # Skip this iteration
  guess = str.parseInt(raw_guess)
  if guess == 1001:
    echo("AAAAAAGGG!")
    break
  elif guess > number:
    echo("Nope. Too high.")
  elif guess < number:
    echo(guess, " is too low")
  else:
    echo("Yeeeeeehaw!")

# Iteration

for i, elem in ["Yes", "No", "Maybe so"]: # Or just `for elem in`
  echo(elem, " is at index: ", i)
for k, v in items(@[(person: "You", power: 100), (person: "Me", power: 9000)]):
  echo v
let myString = """
an <example>
`string` to
play with
""" # Multiline raw string
for line in splitLines(myString):
  echo(line)
for i, c in myString:       # Index and letter. Or `for j in` for just letter
  if i mod 2 == 0: continue # Compact `if` form
  elif c == 'X': break
  else: echo(c)

# Procedures

type Answer = enum aYes, aNo
proc ask(question: string): Answer =
  echo(question, " (y/n)")
  while true:
    case readLine(stdin)
    of "y", "Y", "yes", "Yes":
      return Answer.aYes  # Enums can be qualified
    of "n", "N", "no", "No":
      return Answer.aNo
    else: echo("Please be clear: yes or no")
proc addSugar(amount: int = 2) = # Default amount is 2, returns nothing
  assert(amount > 0 and amount < 9000, "Crazy Sugar")
  for a in 1..amount:
    echo(a, " sugar...")
case ask("Would you like sugar in your tea?")
of aYes:
  add sugar(3)
of aNo:
  echo "Oh do take a little!"
  add sugar()
# No need for an `else` here. Only `yes` and `no` are possible.
#
# FFI
#
# Because Nim compiles to C, FFI is easy:
proc strcmp(a, b: cstring): cint {.importc: "strcmp", nodecl.}
let cmp = strcmp("C?", "Easy!")


Is Nim better than go?

Is the table game is associate with awe-inspiring language and in my opinion higher than Go as a language in varied respects? it's so much less evolved tooling and on-the-market libraries and a way smaller developer community than Go. If that' okay for you, then I'd provide it an attempt.


Nim vs Python| Which language is best?

What is different from the past is that the development of new programming languages ​​is now carried out in C, which is very costly. At first, board games seemed to be just another language among the many possibilities that existed. However, it is not. According to the official documentation, "Nim can be a statically written compilation system programming language." Most likely, the board game was also born from a combination of Python, Ada, and Modula-Palmy variants. The last two may not sound great to most of you, but Python can be the king of scripting. So is it possible for board games to become a new alternative to Python? Does each language target a completely different audience?