LoginSignup
13
0

More than 1 year has passed since last update.

名にし負はば逢坂山のさねかづら人に知られで来るよしもがな

Advent Calendar 2022 74日目1の記事です。
I'm looking forward to 12/25,2022 :santa::santa_tone1::santa_tone2::santa_tone3::santa_tone4::santa_tone5:
私のAdvent Calendar 2022 一覧


はじめに

Elixirを楽しんでいますか:bangbang::bangbang::bangbang:

**がありました。
Elixir 1.13 or laterです。
1.13から追加されています。

**の意味はもちろんべき乗の計算です。
Power operatorです。

base ** eは、

$base^e$

です。

実行

iex> 2 ** 3
8

iex> 2 ** 0
1

内部実装

baseexponentともに整数である場合の実装を抜き出してみます。

lib/elixir/lib/kernel.ex
  def base ** exponent when is_integer(base) and is_integer(exponent) and exponent >= 0 do
    integer_pow(base, 1, exponent)
  end

  # https://en.wikipedia.org/wiki/Exponentiation_by_squaring
  defp integer_pow(_, _, 0),
    do: 1

  defp integer_pow(b, a, 1),
    do: b * a

  defp integer_pow(b, a, e) when :erlang.band(e, 1) == 0,
    do: integer_pow(b * b, a, :erlang.bsr(e, 1))

  defp integer_pow(b, a, e),
    do: integer_pow(b * b, a * b, :erlang.bsr(e, 1))

詳しい説明は省きます。

$2^3$と$2^2$を紙に書いてどう実行されるのかを書き出してみると、なんとなくみえてくるとおもいます。

ちなみに、2 ** 4.0といったように整数以外を含んで使用した場合は、 :math.pow/2 が呼び出されています。


Wrapping up :lgtm::lgtm::lgtm::lgtm::lgtm:

この記事は、Elixir 1.13で追加された**(Power operator)について説明をしました。

Enjoy Elixir:bangbang::bangbang::bangbang:
$\huge{Enjoy\ Elixir🚀}$

以上です。


I organize autoracex.
And I take part in NervesJP, fukuoka.ex, EDI, tokyo.ex, Pelemay.
I hope someday you'll join us.

We Are The Alchemists, my friends!

  1. @kaizen_nagoya さんの「「@e99h2121 アドベントカレンダーではありますまいか Advent Calendar 2020」の改訂版ではありますまいか Advent Calendar 2022 1日目 Most Breakthrough Generator」から着想を得て、模倣いたしました。

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