LoginSignup
9
5

More than 5 years have passed since last update.

elixir tips with with

Posted at

elixir tips with with

これはelixir advent calender 2017の22日目です。

with構文

elixirのwith構文を使う事で、ネストされたcase構文をより簡潔に記述できます。

with パターンマッチ1
     パターンマッチ2
     パターンマッチ3
     ...
do
  処理したいコード
end

withは先頭から順番にパターンマッチを実行し、全てのパターンマッチが成功した時、doの中のコードを実行します。

パターンマッチ中の変数

with構文のdoの中で実行されるコードは、パターンマッチで利用した変数を使う事ができます。

sample1.ex
with one = 1,
     two = 2,
     three = 3
do
  IO.puts one
  IO.puts two
  IO.puts three
end

実行結果

$ elixir sample1.ex
1
2
3
$

パターンマッチの失敗

with構文のパターンマッチが失敗した時は、NoMatchErrorとなります。

sample2.ex
with one = 1,
     two = 2,
     123 = :hoge
do
  IO.puts one
  IO.puts two
end

実行結果

$ elixir sample2.ex
warning: no clause will ever match
  sample2.ex:3

** (MatchError) no match of right hand side value: :hoge
    sample2.ex:3: (file)
    (elixir) lib/code.ex:376: Code.require_file/2
$

<-を使ったwith構文

with構文で=ではなく<-を使って記述すると、パターンマッチに失敗した時の右辺の値を結果として返却します。

sample3.ex
result = with one <- 1,
     two <- 2,
     123 <- :hoge
do
  IO.puts one
  IO.puts two
end

IO.puts result

実行結果

$ elixir sample3.ex
hoge
$

まとめ

上手にwithを使いましょう。

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