8
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.

パイプ演算子 + then/2の組み合わせを学ぶ

8
Last updated at Posted at 2023-10-12

こんにちは!
プログラミング未経験文系出身、Elixirの国に迷い込んだ?!見習いアルケミストのaliceと申します。
今回はthen/2について学んだことをまとめます。

目的

then/2の機能を理解します。

実行環境

Windows 11 + WSL2 + Ubuntu 22.04
Elixir v1.14.3
Erlang v26.0.2
Phoenix v1.7.3

then/2とは?

通常は第一引数にしか渡せないパイプ演算子の左側の値を、第二引数他に渡せる関数。

利用例

File.write/2は第一引数にファイルのパス、第二引数にファイルの中身を指定します。
第一引数のパスに第二引数の中身でファイルを作成します。

oct10/lib/oct10.ex
 defmodule Oct10 do
  def make_a_file do
    body = "Hello, World!"
    File.write("hoge.txt", body)
    File.read("hoge.txt")
  end
 end

実行結果

shell
iex(1)> Oct10.make_a_file
{:ok, "Hello, World!"}

テキストの中身をパイプ演算子で渡したい!(NG例)

File.write/2について、テキストの中身をパイプ演算子を使用して渡したいとします。
しかし、そのままではパイプ演算子の左側の値を、第二引数には渡せません。

oct10/lib/oct10.ex
 defmodule Oct10 do
   def make_ng_file do
     body = "Oh No, World!"
+    body |> File.write("fuga.txt", body) # then句無しではパイプ演算子の左側の要素を第二引数には渡せない
   end
 end

実行結果(NG例)

実際、上記を実行するとこのようなエラーが出ます。

shell
iex(2)> Oct10.make_ng_file
** (FunctionClauseError) no function clause matching in File.normalize_modes/2
...

テキストの中身をthen/2を使用してパイプ演算子で渡す!

これを解決するのがthen/2です。
then/2を使用することでパイプ演算子の左側の値を、第二引数に渡せます!

oct10/lib/oct10.ex
defmodule Oct10 do
   def make_a_file_using_then do
     body = "Hi, World!"
+    body |> then(fn x -> File.write("piyo.txt", x) end)
   end
end

実行結果

shell
iex(3)> Oct10.make_a_file_using_then
{:ok, "Hi, World!"}

パイプ演算子+第一引数以外という組み合わせの際に頻出しそうですね(^▽^)/

~Elixirの国のご案内~

↓Elixirって何ぞや?と思ったらこちらもどぞ。Elixirは先端のアレコレをだいたい全部できちゃいます:laughing::sparkles::sparkles:

↓ゼロからElixirを始めるなら「エリクサーチ」がおすすめ!私もエンジニア未経験から学習中です。

We Are The Alchemists, my friends!:bouquet:1
Elixirコミュニティは本当に優しくて温かい人たちばかり!
私が挫折せずにいられるのもこの恵まれた環境のおかげです。
まずは気軽にコミュニティを訪れてみてください。2

  1. @torifukukaiouさんのAwesomeな名言をお借りしました。Elixirコミュニティを一言で表すと、これに尽きます。

  2. @kn339264さんの素敵なスライドをお借りしました。Elixirコミュニティはいろんな形で活動中!

8
2
2

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
8
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?