小编Git*_*ush的帖子

Clojure 线程优先宏 (->) 与线程最后宏 (->>) 有哪些实际差异?

->我仍然不完全理解两个 Clojure 箭头宏 thread-first和 thread-last 宏之间的区别->>。在阅读https://clojure.org/guides/threading_macros时,我了解到线程优先 ->是单个对象上嵌套操作的替代表达式,每个数据步骤都使用该对象作为输入参数,执行独立的操作。

(defn transformation [object]
  (transform2 (transform1 object)))
Run Code Online (Sandbox Code Playgroud)

变成

(defn transformation [object]
  (-> object
      (transform1)      ;; object as implicit argument
      (transform2)))    ;; object as implicit argument 
Run Code Online (Sandbox Code Playgroud)

当使用威胁最后->>运算符时,每个转换都使用前面转换的输出作为隐式参数:

(defn transformation [object]
  (->> object
       (transform1)      ;; object as implicit argument
       (transform2)))    ;; (transform1 object) as implicit argument
Run Code Online (Sandbox Code Playgroud)

这些差异有什么实际意义?我知道使用威胁优先->对地图和字典进行操作是有意义的,其中每个转换都会创建原始实例的新副本,必须为下一个操作提供该副本。然而,在许多情况下,两个运算符实际上表现相同:

(->> [2 5 4 1 3 6] (reverse) (rest) (sort) (count)) ;; => 5
(->  [2 5 4 …
Run Code Online (Sandbox Code Playgroud)

clojure

4
推荐指数
1
解决办法
1252
查看次数

查找第 n 个元素 - 函数组合

我目前正在阅读“Clojure 的乐趣”一书,第二版。在第 7 章“函数式编程”中,我遇到了以下用于描述函数组合的函数。

(defn fnth [n]
  (apply comp
         (cons first
               (take (dec n) (repeat rest)))))

((fnth 5) '[a b c d e])
;=> e
Run Code Online (Sandbox Code Playgroud)

我不完全了解该功能的机制。尝试在不使用comp的情况下重现内部作用域,该函数会生成一个重复列表:

(take (dec 5) (repeat (rest '[a b c d e])))
;=> ((b c d e) (b c d e) (b c d e) (b c d e))
Run Code Online (Sandbox Code Playgroud)

first使用附加到该重复列表有comp什么意义?这也是输入的函数列表的最后一部分comp吗?

(first (take (dec 5) (repeat (rest '[a b c d e]))))
=> (b c d e)
Run Code Online (Sandbox Code Playgroud)

先感谢您!

clojure

1
推荐指数
2
解决办法
99
查看次数

标签 统计

clojure ×2