5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

草莽Erlang ── 03. 基本的な演算

Last updated at Posted at 2023-01-02

口で言うより行うことがErlang習得への近道と信じています。

算術

四則演算にはそれぞれ演算子 (+, -, *, /)が提供されています。 一点注目すべき点は、/が常に浮動小数を返すことです。

> 2 + 2
4

> 2 - 1.
1

> 2 * 5.
10

> 10 / 5.
2.0

整数同士の割り算や剰余が必要な場合、専用の演算子があります。

> 10 div 5.
2

> 10 rem 3.
1

論理

論理積と論理和にはそれぞれ2種類の演算子があることに注目。

演算子 機能
not 否定
and 論理積(完全評価)
andalso 論理積(短絡評価)
or 論理和(完全評価)
orelse 論理和(短絡評価)
xor 排他的論理和
> not true.
false

> true and false.
false

> true xor false.
true

> true or garbage.
** exception error: bad argument
     in operator  or/2
        called as true or garbage

短絡評価を活用する場合。

> true andalso '元氣があればなんでもできる!'.
'元氣があればなんでもできる!'

> false andalso '元氣があればなんでもできる!'.
false

> false orelse '元氣があればなんでもできる!'.
'元氣があればなんでもできる!'

> true orelse '元氣があればなんでもできる!'.
true

最初の引数は真理値(truefalse)でないと怒られます。

> 42 andalso '元氣があればなんでもできる!'.
** exception error: bad argument: 42

比較

演算子 機能
== 等しい
/= 等しくない
> 〜より大きい
< 〜より小さい
>= 〜以上
=< 〜以下
=:= 厳密に等しい
=/= 厳密に等しくない
> 1 > 2.
false

> 1 /= 2.
true

> 2 == 2.
true

> 2 =< 3.
true

整数と浮動小数を厳密に比べるには=:=を使います。

> 2 == 2.0.
true

> 2 =:= 2.0.
false

比較対象はどんな型でも問題ありません。Erlang ではどんな型でも比較が可能でして、これは特にソートにおいて重宝されます。

number < atom < reference < function < port < pid < tuple < map < list < bitstring

他の言語では中々見られない比較が、Erlang では正当なものとして扱われるのは興味深いです。

> hello > 999.
true

> {hello, world} > [1, 2, 3].
false

文字列の連結

Erlang の文字列はリストですので、文字列の連結は簡単です。

> Aisatsu = "Hello!".
"Hello!"

> Namae = "猪木".
"猪木"

> [Aisatsu, " My name is ", Namae].
["Hello!"," My name is ",[29482,26408]]

> Aisatsu ++ " My name is " ++ Namae.
[72,101,108,108,111,33,32,77,121,32,110,97,109,101,32,105,
 115,32,29482,26408]

io:format/2でフォーマットを指定して標準出力に印字できます。

注意点が一つあります。歴史的な理由なのか知りませんが、何もしてしないと 1 バイトの文字(ISO/IEC 8859-1)しか対応してくれません。多バイトの文字に対応するためには Unicode translation modifier(t)を指定する必要があります。詳しくは原典をご覧ください。

> Greeting = [Aisatsu, " My name is ", Namae].

> io:format("~ts~n", [Greeting]).
Hello! My name is 猪木
ok

> io:format("~s~n", [Greeting]).
** exception error: bad argument
     in function  io:format/2
        called as io:format("~s~n",[["Hello!"," My name is ",[29482,26408]]])
        *** argument 1: failed to format string

Elixirにも挑戦したい

闘魂ElixirシリーズとElixir Schoolがオススメです。

5
2
0

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
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?