gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 21:52:16 24 4
gpt4 key购买 nike

在静态语言中,我可以 replace conditional with polymorphism .

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

我可以在 clojure 中使用什么?

最佳答案

模式匹配和多态分派(dispatch)都可用。

多态调度的两种形式是多方法和协议(protocol)。

leontalbot 给出了一个不错的例子 多种方法根据参数的某些特定属性(可以是类型,但它们可以使用不同的调度函数)调度到特定的实现。换句话说,要决定使用哪个实现,多方法对参数执行一个函数并将其与调度表进行比较。

这是另一个例子:

; Declare multimethod:
(defmulti get-length class)

; Provide implementations for concrete types:
(defmethod get-length java.lang.String [str] (.length str))
(defmethod get-length java.lang.Number [num] (.length (str num)))

; Call it for String:
(get-length "Hello") ;=> 5

; Call it for a Number (works because Long is a subtype of Number):
(get-length 1234) ;=> 4

为了简单起见,我们在这里使用了一些简单的例子,但是 dispatch 函数可能更有趣。再举一个例子,假设我们要根据输入长度选择排序算法:

(defn choose-impl [in]
(cond
(is-sorted? in) :sorted
(< (count in) 10) :bubble
:else :quicksort))

(defmulti my-sort choose-impl)

(defmethod my-sort :sorted [in] in)

(defmethod my-sort :bubble [in] (my-bubble-sort in))

(defmethod my-sort :quicksort [in] (my-quicksort in))

这是人为设计的,您可能不会以这种方式实现它,但我希望它是使用不同调度函数的一个很好的例子。

协议(protocol) 是另一回事,更像是 Java 和其他 OO 语言中已知的接口(interface)。您定义一组构成协议(protocol)的操作,然后为各种类型提供实现。

; Protocol specification:
(defprotocol my-length (get-length [x]))

; Records can implement protocols:
(defrecord my-constant-record [value]
my-length
(get-length [x] value))

; We can "extend" existing types to support the protocol too:
(extend-protocol my-length
java.lang.String
(get-length [x] (.length x))
java.lang.Long
(get-length [x] (.length (.toString x))))

; Now calling get-length will find the right implementation for each:
(get-length (my-constant-record. 15)) ;=> 15

(get-length "123") ;=> 3

(get-length 1234) ;=> 4

最后, 模式匹配 可与非常流行的 core.match 一起使用图书馆:

(doseq [n (range 1 101)]
(println
(match [(mod n 3) (mod n 5)]
[0 0] "FizzBuzz"
[0 _] "Fizz"
[_ 0] "Buzz"
:else n)))

关于clojure - 模式匹配或多态分派(dispatch)是否可用作 clojure 中的条件结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24680322/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com