This blog is my notebook(Python3, LinuxMint, Rust-lang, Nim-lang etc...)
Tuesday, June 5, 2018

FizzBuzz by Nim-lang

Let's FizzBuzz


This program is FizzBuzz by using Nim-lang. Nim-lang is somewhat similar to Python. Both Nim-lang and Python use indentation block. In Nim-lang, it is two spaces(Python is 4 spaces). Variable is two types. var is mutable. let is immutable.
FizzBuzz program is as follows.

# FizzBuzz

let s: int8 = 1
let e: int8 = 15

for i in s..e: ## equal to `for i in 1..15:`
  if i mod 15 == 0:
    echo "FizzBuzz"
  elif i mod 3 == 0:
    echo "Fizz"
  elif i mod 5 == 0:
    echo "Buzz"
  else:
    echo i
Very simple! Let's run it!

$nim c -r fizzbuzz.nim
Hint: used config file '/home/masahiko/.choosenim/toolchains/nim-0.18.0/config/nim.cfg' [Conf]
Hint: system [Processing]
Hint: fizzbuzz [Processing]
CC: fizzbuzz
Hint:  [Link]
Hint: operation successful (11729 lines compiled; 0.352 sec total; 22.121MiB peakmem; Debug Build) [SuccessX]
Hint: /home/masahiko/nim_dev/fizzbuzz  [Exec]
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

It works! nim c -r fizzbuzz.nim is equal to nim compile --run fizzbuzz.nim. In Nim-lang, there are case statements that are not exist in Python.

No comments:

Post a Comment