【问题标题】:How do you flatten nested vectors in Clojure?如何在 Clojure 中展平嵌套向量?
【发布时间】:2016-02-01 19:10:45
【问题描述】:

我有一个叫做历史的原子:

(def history (atom []))

我希望它保存一个向量向量。每个向量都是一个“命令”,历史向量按顺序保存所有命令的历史记录:

(swap! history conj current-command)

我希望它看起来像:

[["move" 20] ["turn" 90]]

但目前它的形式是:

atom[[["move" 20] ["turn" 90] ["turn" 120]]]

我可以提供一些技巧来将其展平为[["move" 20] ["turn" 90]]

【问题讨论】:

    标签: vector clojure flatten


    【解决方案1】:

    您不需要将其展平。您有一个向量,其中包含您想要的向量作为其第一个也是唯一的元素。只需先使用:

    user> (first [[["move" 20] ["turn" 90] ["turn" 120]]])
    [["move" 20] ["turn" 90] ["turn" 120]]
    

    问题是你为什么首先得到那个嵌套向量。您能否分享一段简短的 sn-p 代码,用于生成带有额外嵌套的向量?

    【讨论】:

    • 嗨 Diego,现在我的历史计算结果为 atom[[["move" 20] ["turn" 90] ["turn" 120]]]。如果我这样做(第一次历史),它会抛出错误“不知道如何从:clojure.lang.Atom 创建 ISeq”
    • @truffle 你必须取消一个原子,即(first @history)
    【解决方案2】:

    也许历史原子的初始值不合适

    (def history (atom []))
    (swap!  history conj ["move" 20])
    (swap!  history conj ["move" 30])
    (swap!  history conj ["turn" 50])
    ; [[move 20] [move 30] [turn 50]]
    
    (first @history)
    ; ["move" 20]
    

    编辑:

    (println history)
    ; atom[[["move" 20] ["turn" 90] ["turn" 120]]]
    
    ; but an atom's value should be accessed using the @ mark
    (println @history)
    ; [["move" 20] ["turn" 90] ["turn" 120]]
    

    【讨论】:

      猜你喜欢
      • 2016-09-11
      • 1970-01-01
      • 1970-01-01
      • 2015-01-28
      • 2015-03-28
      • 2016-09-07
      • 2014-04-30
      • 2015-12-03
      • 2016-02-26
      相关资源
      最近更新 更多