You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于Clojure中complement仿写函数及可变参数惯用法的技术问询

模仿Clojure complement函数的opposite实现

我最近正在跟着Clojure官方指南学习,刚好完成了指南里问题8的练习——自己实现一个模仿complement功能的opposite函数,下面是我的解决方案:

(defn opposite [f]
  (fn [& args]
    (not (apply f args))))

为了更好地对比理解,我也贴出Clojure原生complement函数的源码片段:

(defn complement
  "Takes a fn f and returns a fn that takes the same arguments as f,
  has the same effects, if any, and returns the opposite truth value."
  {:added "1.0" :static true}
  [f]
  (fn ([] (not (...))))

简单说下实现思路:opposite接收一个函数f后,返回一个新的匿名函数。这个匿名函数通过& args支持任意数量的输入参数,用apply把参数传递给原函数f,最后用not反转f的返回结果,这和complement的核心逻辑完全一致。原生源码里单独处理了无参的情况,而我的实现用可变参数的方式统一覆盖了所有参数场景,包括无参调用,功能上是完全对齐的。

内容的提问来源于stack exchange,提问作者rwold

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:52:33