LoginSignup
15
0

More than 1 year has passed since last update.

Elixir パイプ演算子 |> の正しい書き方

Last updated at Posted at 2022-12-17

Elixirで一番好きな演算子は、|>(パイプライン演算子) 

書き方が色々あって、迷う事もあったので、The Elixir Style Guide(の日本語訳)をみてみました。
気を付ける点は、次の2点です。詳しい事はガイドライン見てください。

|> を1回だけ使う記述はしない。

|> を1回だけ使う記述は、スタイルガイド違反になります。
使わない記述にするか、2回使う記述にします

使わない記述にする場合

# 悪い例
some_string |> String.downcase

# 良い例
String.downcase(some_string)

2回使う記述にする場合

# 悪い例
String.strip(some_string) |> String.downcase 

# 良い例
some_string
|> String.strip()
|> String.downcase 

1回じゃないからいって、次の記述もダメです

# 悪い例
String.strip(some_string) |> String.downcase |> String.codepoints

# 良い例
some_string |> String.strip |> String.downcase |> String.codepoints

= の右辺として使うときは改行する

= の右辺として使うパイプライン使う事よくありますよね。
スタイルガイドでは、次の記述が推奨されてます。

# パターンマッチの右辺として複数行のパイプラインを使う場合は改行してから書くこと。
sanitized_string =
  some_string
  |> String.downcase
  |> String.strip

参考

https://github.com/christopheradams/elixir_style_guide
https://github.com/kenichirow/elixir_style_guide/blob/master/README-jaJP.md#pipe-operator

15
0
6

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