7
6

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 5 years have passed since last update.

Elixirの文字列と文字リスト

Posted at

ElixirGetting Startedをやろうと思いまして、そのメモです。

はじめに

06. Binaries, strings and char listsです。

UTF-8 and Unicode

  • 文字のコードポイントは、?を使って得られる
  • 文字列をコードポイントごとに分割するにはString.codepoints/1
iex> ?a
97
iex> ?ł
322
iex> ?こ
12371
iex> String.codepoints("こんにちは")
["こ", "ん", "に", "ち", "は"]

Bainaries (and bitstrings)

  • バイナリ = バイト列
  • 文字列 = バイト列
  • バイト列は1バイトずつカンマ区切りで<<...>>で囲む
  • バイト列の結合は<>演算子
  • NULL文字<<0>>を結合して文字列のバイナリ表現をみたりする
iex> <<128, 129>>
<<128, 129>>
iex> <<97, 98>>
"ab"
iex> String.valid? <<128, 129>>
false
iex> String.valid? <<97, 98>>
true
iex> "ab" <> <<0>>
<<97, 98, 0>>
  • 各要素オーバーフローしたビットは捨てられる
  • 各要素何ビットで表現された要素かを::size(bit数)で表現できる
iex> <<256>>
<<0>>
iex> <<256::size(16)>>
<<1, 0>>
iex> <<2::size(1)>>
0
iex> <<12371::utf8>>
"こ"
iex> <256::size(16), 256::size(16)>>
<<1, 0, 1, 0>>
  • "バイナリ"はバイト列(8bitで割り切れるbit列)
iex> is_binary <<1::size(1)>>
false
iex> is_binary <<1::size(7)>>
false
iex> is_binary <<1::size(8)>>
true
iex> is_bitstring <<1::size(1)>>
true
iex> bit_size <<1::size(4)>>
4
  • バイト列/ビット列にもパターンマッチできる
iex> <<0, 1, x>> = <<0, 1, 2>>
<<0, 1, 2>>
iex> x
2

iex> <<0, 1, x>> = <<0, 1, 2, 3>>
** (MatchError) no match of right hand side value: <<0, 1, 2, 3>>

iex> <<0, 1, x::binary>> = <<0, 1, 2, 3>>
<<0, 1, 2, 3>>
iex(155)> x
<<2, 3>>

iex> "he" <> rest = "hello"
"hello"
iex> rest
"llo"

Char lists

  • 文字リストは文字のリスト
  • iexでは、ASCII文字以外が含まれているとコードポイントのリストとして表示される
  • 文字列と文字リストは相互変換できる
iex> 'こんにちは'
[12371, 12435, 12395, 12385, 12399]
iex> is_list 'こんにちは'
true
iex> 'hello'
'hello'

iex> to_char_list "こんにちは"
[12371, 12435, 12395, 12385, 12399]
iex> to_string 'こんにちは'
"こんにちは"
iex> to_string :hello
"hello"
iex> to_string 1
"1"
7
6
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
7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?