Elixir Language
अमृत में बहुरूपता
खोज…
परिचय
बहुरूपता विभिन्न प्रकारों की संस्थाओं के लिए एकल इंटरफ़ेस का प्रावधान है। असल में, यह विभिन्न डेटा प्रकारों को एक ही फ़ंक्शन पर प्रतिक्रिया देने की अनुमति देता है। इसलिए, समान कार्य व्यवहार को पूरा करने के लिए विभिन्न डेटा प्रकारों के लिए समान फ़ंक्शन आकार देता है। अमृत भाषा में स्वच्छ तरीके से बहुरूपता को लागू करने के लिए protocols ।
टिप्पणियों
यदि आप सभी डेटा प्रकारों को कवर करना चाहते हैं तो आप Any डेटा प्रकार के कार्यान्वयन को परिभाषित कर सकते हैं। अंत में, यदि आपके पास समय है, तो Enum और String.Char के स्रोत कोड की जांच करें, जो कोर अमृत में बहुरूपता के अच्छे उदाहरण हैं।
प्रोटोकॉल के साथ बहुरूपता
आइए एक मूल प्रोटोकॉल को लागू करें जो केल्विन और फ़ारेनहाइट तापमान को सेल्सियस में परिवर्तित करता है।
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
अब, हमने केल्विन और फ़ारेनहाइट प्रकारों के लिए अपने कन्वर्टर्स को लागू किया। आइए कुछ रूपांतरण करें:
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