3
0

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

演算子の意味を変えてみる(Elixir)

Posted at

はじめに

  • Elixirのドキュメントを読んでおりました
  • Redefining existing operatorsを読んで「へぇ〜」と思ったので書いておきます
  • +算の結果を-算にしてみます

WrongMath

defmodule WrongMath do
  def a + b, do: a - b
end
  • こんなのを定義するわけです
  • 早速つかってみましょう
iex> defmodule WrongMath do
...>   def a + b, do: a - b
...> end
{:module, WrongMath,
 <<70, 79, 82, 49, 0, 0, 4, 252, 66, 69, 65, 77, 65, 116, 85, 56, 0, 0, 0, 127,
   0, 0, 0, 14, 16, 69, 108, 105, 120, 105, 114, 46, 87, 114, 111, 110, 103, 77,
   97, 116, 104, 8, 95, 95, 105, 110, 102, ...>>, {:+, 2}}

iex> import WrongMath
WrongMath

iex> 1 + 2
** (CompileError) iex:3: function +/2 imported from both WrongMath and Kernel, call is ambiguous

  • 怒られます
    • あいまいは駄目よとのことです
  • 以下のようにすると怒られません
iex> import WrongMath
WrongMath

iex> import Kernel, except: [+: 2]
Kernel

iex> 1 + 2
-1

Wrapping Up

  • ここでは定義済の演算子をoverrideしてみました
  • 公式には、Defining custom operatorsの紹介もあります
  • 使用にあたってはFinal noteをよくよくご参照ください
  • Enjoy Elixir! :rocket::lgtm::rocket::lgtm::rocket:
3
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
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?