Clojure Koans:无法理解有关序列理解的部分

Clojure Koans: Trouble Understanding the Section on Sequence Comprehensions

我是Clojure的新手,所以最近几天我一直在研究Clojure Koans。 直到有关序列理解的部分为止,一切进展顺利。 我在本节中苦苦挣扎。 答案是可用的,但我不明白它们是如何得出这些答案的。 最近两天,我已经阅读了很多有关Clojure的文章,但是它与Ruby的区别非常大,需要花一些时间来理解它。

本节中有五个"问题",我无法弄清楚。 这里有两个使我特别困惑的问题的例子:

1
2
3
4
5
6
7
8
9
10
11
12
"And also filtering"
(= '(1 3 5 7 9)
  (filter odd? (range 10))
  (for [index __ :when (odd? index)]
    index))

"And they trivially allow combinations of the two transformations"
(= '(1 9 25 49 81)
  (map (fn [index] (* index index))
    (filter odd? (range 10)))
  (for [index (range 10) :when __]
    __))

对于具有Clojure经验的人,您能否解释一下他们如何得出此部分的解决方案? 无论我对序列有多少了解,我都无法在本节中全神贯注。 谢谢!


我假设您了解mapfilter函数,并且我猜它们也存在于Ruby中。让我举一个例子,也许可以帮助您理解for在这种情况下的用法。

1
2
3
(map <some function to map a value>
  (filter <some function to return true OR false to filter values>
          ))

上面的代码使用filter对值序列进行了一些过滤,然后使用map函数将过滤后的序列的每个值映射到其他值。

for基本上允许您执行如下所示的操作

1
2
3
(for [index  
     :when <some expression to return true OR false by check index value>]
     (<some expression to map a value i.e transform index to something else>))

我希望以上示例将使您能够映射如何使用for表示mapfilter代码


这种解释很有帮助,并且让我沉迷于Clojure几天后,我对这种语言感到更加自在。为了确保我理解,我将逐步完成这两个测试。

1
2
3
4
5
"And also filtering"
(= '(1 3 5 7 9)
  (filter odd? (range 10))
  (for [index (range 10) :when (odd? index)]
    index))

'(1 3 5 7 9)是0到9之间的所有奇数的列表。
(filter odd? (range 10))返回来自集合(range 10)的所有项的列表,这些项在与odd?对照时评估为true。返回值等于第一个列表。
(for)基本上是for循环。这是迭代的。 (for [index (range 10)] index)会将0到9之间的所有数字绑定到变量index,然后返回index,对吗?
因此(for [index __ :when (odd? index)] index))添加了index是奇数的条件。返回值等于前两个。

那是对的吗?

1
2
3
4
5
6
"And they trivially allow combinations of the two transformations"
(= '(1 9 25 49 81)
  (map (fn [index] (* index index))
    (filter odd? (range 10)))
  (for [index (range 10) :when (odd? index)]
    (* index index)))

在此,map函数具有一个功能。这个匿名函数接受一个参数,并将其自身相乘。 map将将此函数应用于传递的集合中的每个元素。该集合是0到9之间的奇数。

for将在变量index为奇数时将每个数字从0设置为9,然后返回一个懒惰序列,这些数字均平方。

我的解释正确吗?


您了解for的工作原理吗?您是否已在Clojure API文档中阅读了有关内容?如果您知道如何使用for,那么您将无需为"解决"这两个问题而做任何事情。他们是不言而喻的。

这些问题的目的是让您推断for的工作方式。如果他们没有帮助您做到这一点,那么您最好阅读一下该主题。如果您在for上查找了一些信息,但是很难理解,请编辑此问题以确切说明使您感到困惑的问题,我(或其他人)可以尝试解释。