gpt4 book ai didi

clojure - Clojure 中函数参数排序的经验法则

转载 作者:行者123 更新时间:2023-12-04 22:18:21 29 4
gpt4 key购买 nike

在 Clojure 核心中决定参数函数顺序的规则是什么(如果有的话)?

  • 类似 map 的函数和 filter期望数据结构作为最后一个
    争论。
  • 类似 assoc 的函数和 select-keys期待数据
    结构作为第一个参数。
  • 类似 map 的函数和 filter期待一个函数作为第一个
    争论。
  • 类似 update-in 的函数期望一个函数作为最后一个参数。

  • 这在使用线程宏时会引起痛苦(我知道我可以使用 as-> )那么这些决定背后的原因是什么?也很高兴知道这样我的函数可以尽可能地符合伟人编写的函数。

    最佳答案

    对集合进行操作的函数(因此获取和返回数据结构,例如 conjmergeassocget )获取集合 第一 .

    对序列进行操作的函数(因此采用并返回对数据结构的抽象,例如 mapfilter )采用序列 最后 .

    Becoming more aware of the distinction [between collection functions and sequence functions] and when those transitions occur is one of the more subtle aspects of learning Clojure.



    (亚历克斯·米勒,在 this mailing list thread 中)

    这是使用 Clojure 的 sequence API 智能工作的重要部分.例如,请注意,它们在 Clojure Cheatsheet 中占据不同的部分。 .这不是一个小细节。这是如何组织功能以及如何使用它们的核心。

    查看此 description of the mental model 可能会有所帮助在区分这两种功能时:

    I am usually very aware in Clojure of when I am working with concrete collections or with sequences. In many cases I find the flow of data starts with collections, then moves into sequences (as a result of applying sequence functions), and then sometimes back to collections when it comes to rest (via into, vec, or set). Transducers have changed this a bit as they allow you to separate the target collection from the transformation and thus it's much easier to stay in collections all the time (if you want to) by apply into with a transducer.

    When I am building up or working on collections, typically the code constructing it is "close" and the collection types are known and obvious. Generally sequential data is far more likely to be vectors and conj will suffice.

    When I am thinking in "sequences", it's very rare for me to do an operation like "add last" - instead I am thinking in whole collection terms.

    If I do need to do something like that, then I would probably convert back to collections (via into or vec) and use conj again.



    Clojure 的 FAQ 有几个不错的 rules of thumb and visualization techniques获得集合/第一个参数与序列/最后一个参数的直觉。

    关于clojure - Clojure 中函数参数排序的经验法则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50275513/

    29 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com