【问题标题】:Clojure Koans: Trouble Understanding the Section on Sequence ComprehensionsClojure Koans:难以理解序列理解部分
【发布时间】:2012-10-16 14:19:35
【问题描述】:

我是 Clojure 的新手,所以最近几天我一直在查看 Clojure Koans。在section on sequence comprehensions 之前,一切进展顺利。我在这部分苦苦挣扎。 answers 可用,但我不明白他们是如何获得这些答案的。过去两天我读了很多关于 Clojure 的文章,但它与 Ruby 有很大不同,以至于我需要一段时间才能理解它。

该部分中有五个“问题”,我无法弄清楚。以下是两个让我特别困惑的问题示例:

"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 经验的人,您能否解释一下他们是如何得出本节的解决方案的?不管我读了多少关于序列的内容,我都无法理解这一节。谢谢!

【问题讨论】:

    标签: clojure sequences


    【解决方案1】:

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

    (map <some function to map a value> 
      (filter <some function to return true OR false to filter values>
              <a sequence of values>))
    

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

    for 基本上允许你做同样的事情,如下所示

    (for [index <a sequence of values> 
         :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>))
    

    我希望上面的例子能让你能够映射mapfilter代码是如何使用for表达的

    【讨论】:

    • 谢谢,看到那些像这样打字的人很有帮助。
    【解决方案2】:

    这种解释很有帮助,在我又沉浸在 Clojure 中几天之后,我对这种语言感觉更舒服了。为了确保我理解,我将完成这两个测试。

    "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? 核对时评估为真。返回值等于第一个列表。
    (for) 基本上是一个 for 循环。它是迭代的。 (for [index (range 10)] index) 会将 0 到 9 之间的所有数字绑定到变量 index,然后返回 index,对吗? 所以(for [index __ :when (odd? index)] 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 (odd? index)]
        (* index index)))
    

    这里map 函数接受一个函数。这个匿名函数接受一个参数并将该参数与自身相乘。 map 将把这个函数应用到它传递的集合中的每个元素。该集合是 0 到 9 之间的奇数。

    for 会将 0 到 9 之间的每个数字设置为变量 index,当它是奇数时,然后返回每个数字平方的惰性序列。

    我的解释正确吗?

    【讨论】:

      【解决方案3】:

      你了解for 的工作原理吗?你有read about it in the Clojure API docs吗?如果您知道如何使用for,那么您将无需做任何事情来“找到”这两个问题的解决方案;它们将是不言而喻的。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-01
        • 1970-01-01
        • 2015-07-25
        • 2017-10-24
        • 1970-01-01
        • 2010-10-28
        相关资源
        最近更新 更多