为什么在clojure.core中这样部分地实现 [英] Why such implementation of partial in clojure.core

查看:49
本文介绍了为什么在clojure.core中这样部分地实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 cojure.core 中偶然发现了 partial 函数的实现。看起来是这样的:

I stumbled across implementation of partial function in cojure.core. It looks like this:

(defn partial
  "Takes a function f and fewer than the normal arguments to f, and
  returns a fn that takes a variable number of additional args. When
  called, the returned function calls f with args + additional args."
  {:added "1.0"
   :static true}
  ([f] f)
  ([f arg1]
   (fn [& args] (apply f arg1 args)))
  ([f arg1 arg2]
   (fn [& args] (apply f arg1 arg2 args)))
  ([f arg1 arg2 arg3]
   (fn [& args] (apply f arg1 arg2 arg3 args)))
  ([f arg1 arg2 arg3 & more]
   (fn [& args] (apply f arg1 arg2 arg3 (concat more args)))))

为什么它可以有多个奇偶校验选项?仅仅是性能优化,所以在大多数情况下不会调用 concat 吗?

Why it has several parity options if it could have one? Is it just performance optimisation so concat doesn't get called in most cases?

我的意思是否则看起来像这样,对吧?

I mean it could look like this otherwise, right?

(defn partial
  ([f] f)
  ([f & more]
   (fn [& args] (apply f (concat more args))))
  )

我还注意到其他几个函数遵循相同的模式。

I also noticed several other functions follow the same pattern.

推荐答案

是的,这是性能优化。

我不只是不打电话给 concat -而是& 也需要创建一个集合。 Clojure核心库倾向于认真考虑性能,但前提是该语言的基本构建块将出现在每个人的性能瓶颈中。

I'ts not just about not calling concat - it's about the fact that & in the argument list requires a collection to be created as well. The clojure core libraries tend to take performance seriously, under the assumption that the basic building blocks of the language will be present in everyone's performance bottleneck.

这篇关于为什么在clojure.core中这样部分地实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆