【问题标题】:Getting ith element of a sequence in Clojure在 Clojure 中获取序列的第 i 个元素
【发布时间】:2021-11-18 00:01:04
【问题描述】:

我目前正在学习 clojure,我需要帮助。 说如果我有下面是p,

{:variable "x", :coef (2 5 7 13)}

我可以通过 (last (last p)) 访问 coef 并且可以通过这样做来迭代它的范围

(for [i (range(count (last (last p))))]
        i
        )

现在,我想访问每个第 i 个 coef 元素。例如,如果 i 是 0,那么我想得到 2,如果 i 是 3,那么我想得到 13)。

【问题讨论】:

  • 您应该使用(:coef p)(get p :coef) 访问密钥:coef。以声明顺序维护键的小地图是您不能依赖的实现细节。
  • 我把标题中lazy seq中的lazy去掉了,因为这个问题和lazy seq无关。

标签: clojure


【解决方案1】:

使用与您当前拥有的 p 相同的定义:

user=> (def p {:variable "x", :coef '(2 5 7 13)})
#'user/p

user=> (defn nth-coef [p i] (nth (get p :coef) i))
#'user/nth-coef

user=> (nth-coef p 0)
2
user=> (nth-coef p 1)
5

如果p 在系数中有vector,您可以使用get-in

user=> (def p {:variable "x", :coef [2 5 7 13]})
#'user/p

user=> (get-in p [:coef 1])
5

【讨论】:

    猜你喜欢
    • 2013-08-06
    • 2013-05-13
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-27
    • 2014-11-04
    • 2019-04-16
    相关资源
    最近更新 更多