There's an echo in my head

日々のメモ。

ErlangでHello, world

RiakのサンプルコードがErlangで書かれていたので、Getting Startedとかこれから15分でErlangを始めるための資料とかを読みながら。

Homebrewでインストール。

$ brew install erlang

REPLについて。

  • $ erlで起動
  • halt().、もしくはCtrl+\で終了
  • バージョンは$ erl -version

たとえば

$ erl
Erlang R15B02 (erts-5.9.2) [source] [64-bit] [smp:4:4] [async-threads:0] [hipe] [kernel-poll:false] [dtrace]

Eshell V5.9.2  (abort with ^G)
1> 1+1. % 式.で式を評価
2
2> halt().
$ 

さてコード。

% single line comment
% 日本語もOK(UTF-8のみ??)

% `hello`モジュールを宣言
% 1ファイル1モジュール、ファイル名は慣習的に`モジュール名.erl`とする。
% なのでこのコードは`hello.erl`として保存する。
-module(hello).

% モジュールが引数0個(引数をとらない)関数`hello_world`を持つことを宣言
-export([hello_world/0]).

% hello_world()が呼ばれたら文字列を書き出す
hello_world() -> io:write("Hello, world\n").

これを前述のREPL上からコンパイルして実行してみる。

$ cd hello.erlのあるディレクトリ
$ erl
Erlang R15B02 (erts-5.9.2) [source] [64-bit] [smp:4:4] [async-threads:0] [hipe] [kernel-poll:false] [dtrace]

Eshell V5.9.2  (abort with ^G)
1> c(hello). % コンパイル
{ok,hello}  % コンパイル成功!`hello.beam`というファイルができてる
2> hello:hello_world(). % `モジュール:関数()`で呼び出す
Hello, world!
ok
3> 
このブログに出てくるコードスニペッツは、引用あるいは断りがない限りMITライセンスです。