LoginSignup
26
18

More than 5 years have passed since last update.

nim入門

Last updated at Posted at 2017-12-04

今回はマイナー言語nimについて扱おうと思います。ユーザーが少ないせいで、記事が少ないので書きました。
さて、nimという言語がどういうものだか知っている人はいますか?おそらく知らない人のほうが多いんじゃないでしょうか?nimは一言で言えばインタープリンタ型言語っぽくかけるコンパイラ型言語です。
簡単にそれを説明します

main関数のいらないコンパイラ型言語

C++, Java, C#など、おそらく皆さんの知っているコンパイラ型言語のほとんどはmain関数を必要とするものが多いと思います。しかし、nimは多くのインタープリンタ型言語と同じでmain関数を必要としません。そのため個人的には書き方が多くのインタープリンタと似ていると個人的には思いました。

installation

ubuntuなら

sudo apt-get install nim

OS Xなら

brew install nim

でインストールできます。

hello world

hello_world.nim
echo "hello world"

これは簡単ですね。nim compile hello_world.nimでコンパイルすることができます。
同時に実行もさせたい場合は--runというオプションをつけるだけです。

int (整数)型

int.nim
import math

var x, y : int
x = 2
y = 3
echo x + y # 足し算
echo x - y # 引き算
echo x * y # 掛け算
echo x / y # 割り算
echo x div y # 割り算の商
echo x mod y # 割り算のあまり
echo x ^ y # べき乗
echo x and y # 論理和
echo x or y # 論理積
echo x xor y # 排他的論理和
echo (not x) # ビット反転
echo x shl y # 左シフト
echo x shr y # 右シフト
echo int("100") # 文字列から数値への変換
echo int("hello world"[0]) # ascii codeの取得

文字列型

string.nim
import strutils
echo "hello world     ".strip() # 先頭と終わりの半角空白を取り除く
echo "hello world".len() # 文字列の長さ
echo "hello world".split(' ') # 文字列を空白で分割
echo(@["hello", "world"].join(" ")) # 文字列連結
echo "hello world"[0] # n番目の文字
echo "hello world"[2..7] # 部分文字列
echo "hello world".repalce("hello", "hola") # 文字列置換
echo "$1 eats $2." % ["The cat", "fish"]
echo "hello " & "world" # 文字列連結

Sequence(配列その2)

多分これって動的配列のことですかね

sequence.nim
import sequtils
var a : seq[int]
echo concat(@[3, 5, 7], @[9, 11, 13], @[15, 17, 19, 21]) 
# 配列の結合 可変長引数なので引数の数はいくつでもいい
echo(@[1, 2, 3].map(proc(x: int): int = 2 * x) 
# map関数も実装されている ここではすべての要素を2倍にしている
echo(@[1, 2, 3, 4, 5, 6, 7].filter(proc(x: int): bool = x mod 2 == 0) 
# 偶数だけを取り出すフィルター

関数(?)をつかったhello world

function.nim
proc hello_world() = echo "hello world" # ここでは返り値、引数ともにvoid
hello_world()

proc hello_world2(str : string) : string = str # 引数、返り値ともにstring
echo hello_world2("hello world")

proc hello_world3(a : string; b : string) = echo a & " " & b # 引数が2つで両方ともstring, 返り値がvoid
hello_world3("hello", "world")

proc hello_world4(a : string; b : string) =
     echo a
     echo " "
     echo b
     # 関数の終わりはインデントで管理
hellow_world4("hello", "world")

proc hello_world5() : string = 
      echo "hello"
      echo "world" 
      "hello world" # 最後に評価された式がそのまま返り値になる。
echo hello_world5() # hello worldと表示される
26
18
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
26
18