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

查看:18
本文介绍了为什么在 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.

推荐答案

是的,这是一个性能优化.

Yes, it's a performance optimization.

我不仅仅是不调用 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天全站免登陆