简体   繁体   English

Clojure中的模式匹配函数?

[英]Pattern matching functions in Clojure?

I have used erlang in the past and it has some really useful things like pattern matching functions or "function guards". 我过去使用过erlang,它有一些非常有用的功能,如模式匹配功能或“功能保护”。 Example from erlang docs is: erlang文档的示例是:

fact(N) when N>0 -> 
    N * fact(N-1); 
fact(0) ->      
    1.    

But this could be expanded to a much more complex example where the form of parameter and values inside it are matched. 但是这可以扩展到一个更复杂的例子,其中的参数和值的形式是匹配的。

Is there anything similar in clojure? 在clojure中有类似的东西吗?

There is ongoing work towards doing this with unification in the core.match ( https://github.com/clojure/core.match ) library. 目前正在努力通过core.match( https://github.com/clojure/core.match )库中的统一来实现这一目标。

Depending on exactly what you want to do, another common way is to use defmulti/defmethod to dispatch on arbitrary functions. 根据您想要做的事情,另一种常见的方法是使用defmulti / defmethod来调度任意函数。 See http://clojuredocs.org/clojure_core/clojure.core/defmulti (at the bottom of that page is the factorial example) 请参阅http://clojuredocs.org/clojure_core/clojure.core/defmulti (该页面底部是阶乘示例)

I want to introduce defun , it's a macro to define functions with pattern matching just like erlang,it's based on core.match. 我想介绍defun ,它是一个宏来定义函数与模式匹配就像erlang一样,它基于core.match。 The above fact function can be wrote into: 以上事实函数可写入:

(use 'defun)
(defun fact
  ([0] 1)
  ([(n :guard #(> % 0))] 
    (* n (fact (dec n)))))

Another example, an accumulator from zero to positive number n: 另一个例子,从零到正数n的累加器:

(defun accum
  ([0 ret] ret)
  ([n ret] (recur (dec n) (+ n ret)))
  ([n] (recur n 0)))

More information please see https://github.com/killme2008/defun 更多信息请参阅https://github.com/killme2008/defun

core.match is a full-featured and extensible pattern matching library for Clojure. core.match是Clojure的全功能和可扩展模式匹配库。 With a little macro magic and you can probably get a pretty close approximation to what you're looking for. 有一点宏观魔法,你可能会得到一个非常接近你正在寻找的东西。

Also, if you want to take apart only simple structures like vectors and maps (any thing that is sequence or map, eg record, in fact), you could also use destructuring bind . 此外,如果你想只拆分简单的结构,如矢量和地图(任何事物,如序列或地图,例如记录,事实上),你也可以使用destructuring bind This is the weaker form of pattern matching, but still is very useful. 这是较弱的模式匹配形式,但仍然非常有用。 Despite it is described in let section there, it can be used in many contexts, including function definitions. 尽管在那里的let部分对它进行了描述,但它可以在许多上下文中使用,包括函数定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM