简体   繁体   English

Clojure vector->使用#和%语法糖的矢量功能?

[英]Clojure vector -> vector function using # and % syntax sugar?

Is it possible to code using #, %1, %2 for the below? 是否可以在下面使用#,%1,%2进行编码?

(defn fib-step [[a b]]
  [b (+ a b)])

(defn fib-seq []
  (map first (iterate fib-step [0 1])))

user> (take 20 (fib-seq))
(0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181)

In short, I'd like to know how to write vector -> vector function using # and % syntax sugar. 简而言之,我想知道如何使用#和%语法糖编写vector-> vector函数。

Thanks 谢谢

You can easily produce a vector using the #() reader form with the -> threading macro. 您可以使用带有( ->线程宏的#()阅读器形式轻松生成矢量。 For example, the following two functions are equivalent: 例如,以下两个功能是等效的:

(fn [a b] [b a])
#(-> [%2 %])

However, if you need to do destructuring, as in your case, you're best off just sticking with one of the fn forms with an explicit parameter list. 但是,如果您需要进行解构(如您的情况),则最好只使用带有显式参数列表的fn形式之一。 The best you'd get with #() is something like this: #()的最佳效果是:

#(-> [(% 1) (+ (% 0) (% 1))])

or 要么

#(-> [(% 1) (apply + %)])

Using the higher-order juxt function is another nice way to create vectors, but unfortunately in this case it doesn't buy you much either: 使用高阶juxt函数是创建向量的另一种不错的方法,但是不幸的是,在这种情况下,它也买不到东西:

(def fib-step (juxt second #(apply + %)))

I think out of all the options, using fn is still the best fit because of its easy support for destructuring: 我认为,在所有选项中,使用fn仍然是最合适的选择,因为它易于支持解构:

(fn [[a b]] [b (+ a b)])

Here is the code: 这是代码:

(def step #(-> [(% 1) (+ (% 0) (% 1))]))
(def fib #(map first (iterate step [0 1])))

(println 
 (take 20 (fib))
)

or 要么

(def step #(-> [(% 1) (+ (% 0) (% 1))]))
(def fib (->> [0 1]
              (iterate step)
              (map first)))

(println
  (->> fib 
       (take 20))
))

I would suggest making fib-step take 2 parameters rather than a vector as that would make things more clear that this function need two values whereas a vector as param means it can take any number of values as param (in the form of the vector). 我建议使fib-step接受2个参数而不是向量,因为这样会使事情更加清楚,该函数需要两个值,而向量作为param意味着它可以接受任意数量的值作为param(以向量的形式) 。

(def fib-step #(-> [%2 (+ %1 %2)]))

(defn fib-seq []
  (map first (iterate (partial apply fib-step) [0 1])))

I think using the vector function is clearer than the (-> [...]) "trick": 我认为使用vector功能比(-> [...]) “技巧”更清晰:

#(vector (% 1) (apply + %))

Though in this instance, with destructuring, I'd just use a named function or (fn [...] ...) anyway. 尽管在这种情况下,通过解构,无论如何我还是只使用命名函数或(fn [...] ...)

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

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