Elixir Language
エリキシルの多型
サーチ…
前書き
多態性は、異なるタイプのエンティティへの単一のインタフェースを提供することです。基本的には、異なるデータ型が同じ関数に応答することができます。したがって、同じ機能が同じデータ型で同じ動作を実現します。エリクシール言語には、多形性をきれいに実装protocolsためのprotocolsがありprotocols 。
備考
すべてのデータ型をカバーする場合は、 Anyデータ型の実装を定義できます。最後に、時間があれば、 EnumとString.Charのソースコードを確認してください。これは、コアのElixirの多型の良い例です。
プロトコルによる多型
ケルビンと華氏の温度を摂氏に変換する基本的なプロトコルを実装しましょう。
defmodule Kelvin do
defstruct name: "Kelvin", symbol: "K", degree: 0
end
defmodule Fahrenheit do
defstruct name: "Fahrenheit", symbol: "°F", degree: 0
end
defmodule Celsius do
defstruct name: "Celsius", symbol: "°C", degree: 0
end
defprotocol Temperature do
@doc """
Convert Kelvin and Fahrenheit to Celsius degree
"""
def to_celsius(degree)
end
defimpl Temperature, for: Kelvin do
@doc """
Deduct 273.15
"""
def to_celsius(kelvin) do
celsius_degree = kelvin.degree - 273.15
%Celsius{degree: celsius_degree}
end
end
defimpl Temperature, for: Fahrenheit do
@doc """
Deduct 32, then multiply by 5, then divide by 9
"""
def to_celsius(fahrenheit) do
celsius_degree = (fahrenheit.degree - 32) * 5 / 9
%Celsius{degree: celsius_degree}
end
end
今度は、KelvinとFahrenheitタイプのコンバータを実装しました。コンバージョンをいくつか作ろう:
iex> fahrenheit = %Fahrenheit{degree: 45}
%Fahrenheit{degree: 45, name: "Fahrenheit", symbol: "°F"}
iex> celsius = Temperature.to_celsius(fahrenheit)
%Celsius{degree: 7.22, name: "Celsius", symbol: "°C"}
iex> kelvin = %Kelvin{degree: 300}
%Kelvin{degree: 300, name: "Kelvin", symbol: "K"}
iex> celsius = Temperature.to_celsius(kelvin)
%Celsius{degree: 26.85, name: "Celsius", symbol: "°C"}
to_celsius関数の実装がない他のデータ型を変換しようとしましょう:
iex> Temperature.to_celsius(%{degree: 12})
** (Protocol.UndefinedError) protocol Temperature not implemented for %{degree: 12}
iex:11: Temperature.impl_for!/1
iex:15: Temperature.to_celsius/1
Modified text is an extract of the original Stack Overflow Documentation
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow