Clojure字符串索引超出范围:-1

时间:2017-04-15 13:39:06

标签: string clojure substring

我正在尝试将clojure地图转换为Mathematica图表,地图关系

{:60 [:34], :14 [:13], :39 [], :37 [:21], :59 [], :27 [:26 :32], :42 [], :45 [], :31 [:28], :40 [], :18 [:19], :52 [], :12 [:11], :11 [:9 :12 :17 :16], :24 [:25], :10 [:9], :21 [:16 :37 :36], :56 [], :23 [:25], :13 [:14], :0 [:1], :58 [], :30 [:29], :38 [], :53 [], :4 [:2 :5 :54], :43 [], :57 [], :26 [:28], :16 [:11 :5 :21 :34], :44 [], :7 [:8 :9], :35 [], :55 [], :1 [:0], :50 [], :8 [:7], :36 [:21], :22 [], :47 [], :25 [:24], :9 [:7 :10 :11], :20 [:19], :17 [:11], :46 [], :32 [:33 :35 :34], :49 [], :28 [], :48 [], :19 [:18 :20], :2 [:3 :4], :5 [:4 :6 :16 :15], :41 [], :15 [:5], :3 [], :6 [:5], :33 [], :51 [], :54 [], :29 [:30], :34 []}

函数定义为

 (defn relations-export []
  (do
    (def temp "{")
    (for [x relations]
      (map (fn [l] (def temp (str temp (clojure.string/replace (str (first x) " -> " l ", ") ":" "")))) (second x)))
    (def temp (str (subs temp 0 (- (count temp) 2)) "}" ))
    )
  )

它应该给出一个像

这样的字符串
"{60 -> 34, 14 -> 13, 37 -> 21, 27 -> 26, 27 -> 32, 31 -> 28, 18 -> 19, 12 -> 11, 11 -> 9, 11 -> 12, 11 -> 17, 11 -> 16, 24 -> 25, 10 -> 9, 21 -> 16, 21 -> 37, 21 -> 36, 23 -> 25, 13 -> 14, 0 -> 1, 30 -> 29, 4 -> 2, 4 -> 5, 4 -> 54, 26 -> 28, 16 -> 11, 16 -> 5, 16 -> 21, 16 -> 34, 7 -> 8, 7 -> 9, 1 -> 0, 8 -> 7, 36 -> 21, 25 -> 24, 9 -> 7, 9 -> 10, 9 -> 11, 20 -> 19, 17 -> 11, 32 -> 33, 32 -> 35, 32 -> 34, 19 -> 18, 19 -> 20, 2 -> 3, 2 -> 4, 5 -> 4, 5 -> 6, 5 -> 16, 5 -> 15, 15 -> 5, 6 -> 5, 29 -> 30}"

但它运行为CompilerException java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:-1,编译:(form-init2059367294355507639.clj:269:20)

问题是我逐行测试(do& expr)中的代码,它们按预期工作,但是当我把它们放在这个函数中时,我收到了一个错误。

1 个答案:

答案 0 :(得分:3)

似乎你缺少一些Clojure的基础知识,因为你正在使用def-in-def。这是你可能应该开始的地方。

将问题分解为较小的问题而不是将它们直接放在一起可能是个好主意。因此,第一步是创建组合,然后将它们转换为所需的字符串组合,并在最后一步创建完整的字符串。这看起来像这样:

(require '[clojure.string])

(defn relations-export [data]
  (let [combinations (for [[k vs] data, v vs] [k v])
        comb-strings (map (fn [[k v]] (str (name k) " -> " (name v))) combinations)]
    (str "{" (clojure.string/join ", " comb-strings) "}")))

来自评论的应用建议,感谢@Thumbnail

请使用Clojure基础知识来开始使用该语言。一个好的起点肯定是braveclojure.com