相关疑难解决方法(0)

Clojure defprotocol作为表达问题的解决方案

在"Clojure的喜悦"一书中,defprotocol提供了表达式问题的解决方案- "希望为现有的具体类实现一组现有的抽象方法,而不必更改定义任何一个的代码."

给出的例子如下:

(defprotocol Concatenatable
  (cat [this other]))

(extend-type String
  Concatenatable
  (cat [this other]
    (.concat this other)))

(cat "House" " of Leaves")
;=> "House of Leaves"

(extend-type java.util.List
  Concatenatable
  (cat [this other]
    (concat this other)))

(cat [1 2 3] [4 5 6])
;=> (1 2 3 4 5 6)
Run Code Online (Sandbox Code Playgroud)

有人认为这在Java这样的语言中是不可能的,但它与以下内容有何不同?

public class Util {
  public static String cat(final String first,
                           final String second) {
    return first.concat(second);
  }

  public static <T> List<T> cat(final List<T> first,
                                final List<T> …
Run Code Online (Sandbox Code Playgroud)

polymorphism clojure

9
推荐指数
1
解决办法
1811
查看次数

模式匹配或多态分派是否可用作clojure中的条件结构?

在静态语言中,我可以用多态替换条件.

在像erlang这样的语言中,我可以使用模式匹配而不是if else.

我在clojure中可以使用什么?

clojure

4
推荐指数
2
解决办法
653
查看次数

标签 统计

clojure ×2

polymorphism ×1