LoginSignup
1
0

More than 5 years have passed since last update.

Elixir ~基本概要つづき~

Posted at

ここまでのあらまし

こちらのサイト を参照しながらひさびさにQiitaドキュメントをしたためました。

続きをいってみようと思います。

本題

無名関数から。

iex > sum = fn(a, b) -> a + b end
#Function<12.128620087/2 in :erl_eval.expr/5>

呼び出し

iex > sum.(1, 2) 
3

変数に関数が収められているかを調べるのがis_function/1、アリティの数を調べるのがis_function/2

iex > is_function(sum)
true
iex > is_function(sum,2)
true

以前わたしのドキュメントで扱った&記法。

iex > sum = &(&1 + &2)
&:erlang.+/2
iex > sum.(3,4)
7

ここからはリストについて。

iex > list = [3.14, :pie, true, "Apple"]
[3.14, :pie, true, "Apple"]
iex > length(list)
4

++や--といった演算子でリストに要素を加えたり差し引いたりすることもできる模様です。

iex > list ++["Kento"]
[3.14, :pie, true, "Apple", "Kento"]
iex > ["Π"]++
... > ["Π"]++ list
["Π", "Π", 3.14, :pie, true, "Apple"]
iex > list --["Π","Kento"]
[3.14, :pie, true, "Apple"]

この際注意しなければならないのはリスト演算子がリストの中身を書き換えるのではないということで、返ってくるのは新しいリストだということです。
これがイミュータブル(immutable、公式ドキュメントでしばしば出てくる単語で)ということ、データの書き換えではなくデータの変換が行われている。
これは地味なようで非常に重要なポイントだと思われます。

シングルクオーテーションとダブルクオーテーションで囲ったものの違い。

iex > i("hello")
Term
  "hello"
Data type
  BitString
Byte size
  5
Description
  This is a string: a UTF-8 encoded binary. It's printed surrounded by
  "double quotes" because all UTF-8 encoded codepoints in it are printable.
Raw representation
  <<104, 101, 108, 108, 111>>
Reference modules
  String, :binary
Implemented protocols
  Collectable, IEx.Info, Inspect, List.Chars, String.Chars
iex > i('Hello')
Term
  'Hello'
Data type
  List
Description
  This is a list of integers that is printed as a sequence of characters
  delimited by single quotes because all the integers in it represent valid
  ASCII characters. Conventionally, such lists of integers are referred to
  as "charlists" (more precisely, a charlist is a list of Unicode codepoints,
  and ASCII is a subset of Unicode).
Raw representation
  [72, 101, 108, 108, 111]
Reference modules
  List
Implemented protocols
  Collectable, Enumerable, IEx.Info, Inspect, List.Chars, String.Chars

詳しいことを出てきたinfoの英文で追いかけるのは今回は割愛しますが、ふたつは違う。興味深いです。

タプルへと行きます。
要素を中括弧で囲い、カンマ区切りにしたもの。
要素の数を測るには、tuple_size/1。

iex > tuple = {3.14, :pie, true, "Apple"}
{3.14, :pie, true, "Apple"}
iex > tuple_size(tuple)
4

elem/2関数で指定した要素の取り出し、put_elem/3で、指定した要素の置き換え。

iex > elem(tuple,3)           
"Apple"
iex > put_elem(tuple,3,"Orange")
{3.14, :pie, true, "Orange"}

編集後記

Elixirの型の基本について、2回に渡ってさらってゆくことができました。
参照させていただいているページがElixirの基礎について参考書のような構造になっているので、引き続き備忘録をしたためながらやってゆこうと思います。

うまずたゆまず、頑張ります。
Kento Mizuno

1
0
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
1
0