Polymorphism in Clojure

Web Technology   Digital Transformation Technology Artificial Intelligence Technology   Natural Language Processing Technology   Semantic Web Technology   Deep Learning Technology   Online Learning & Reinforcement Learning Technology  Chatbot and Q&A Technology   User Interface Technology   Knowledge Information Processing Technology   Reasoning Technology  Clojure Programming

In the previous article, we discussed the handling of classes as OOP in Clojure. In this article, we will discuss Polymorphism, which is another feature of OOP. According to the wiki, “Polymorphism is a property of the type system of a programming language that allows each element (constant, variable, expression, object, function, method, etc.) of the programming language to belong to multiple types. It is also called polymorphism, polymorphism, polymorphism, and diversity. Its synonyms are monomorphism, monomorphism, and monomorphism, which refer to the property that each element of a programming language belongs to only one type. Monomorphism is defined in a very difficult way.

Monomorphism means that each function or procedure is associated with a uniquely identifiable name. Monomorphism means that each function or procedure is associated with a uniquely identified name, i.e., different names are used to achieve different behaviors. Its opposite, polymorphism, is defined as the use of the same name to achieve different behaviors.

Let’s look at this in concrete terms in Clojure code. First of all, the monomorphic code looks like the following.

(defn freee-amount [percentage user]
   (float (* 0.01 percentage (:salary user))))
(defn affiliate-free-cond [user]
   (cond
      (= :google.com (:refer user)) (free-amount 0.01 user)
      (= :mint.com (:refer user)) (free-amount 0.03 user)
      :default (free-amount 0.02 user)))

It is a function that contains branches to achieve different functions. In contrast, the polymorphic code using defmulti and defmethod is as follows.

(defmulti affiliate-fee :referrer)
(defmethod affiliate-fee :mint.com [user]
  (fee-amount 0.03 user))
(defmethod affiliate-fee :google.com [user]
  (fee-amount 0.01 user))
(defmethod affiliate-fee :default [user]
  (fee-amount 0.02 user))

(def user-1 {:login "rob" :referrer :mint.com :salary 100000})
(def user-2 {:login "kyle" :referrer :google.com :salary 90000})
(def user-3 {:login "celeste" :referrer :yahoo.com :salary 70000})

(affiliate-fee user-1)
;;->30.0
(affiliate-fee user-2)
;;->9.0
(affiliate-fee user-3)
;;->14.0

The above defines a single function name, affiliate-free, with a defmulti function, and each variation is defined with a defmethod. With these, it becomes available to process classes user-1, user-2, and user-3 with different attribute values separately in each case at once. From the OOP point of view, this is “unifying the names of similar methods between different classes”.

コメント

Exit mobile version
タイトルとURLをコピーしました