2017-04-15 56 views
0

我想一個Clojure的地圖轉換爲數學圖形,地圖關係Clojure的字符串索引超出範圍:-1

{: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,編譯:(形狀init2059367294355507639.clj:269:20)

問題是我在測試的代碼(做&表達式)由線線他們按預期工作,但是當我把它們放在這個函數中時,我得到了一個錯誤。

+0

要回到你原來的問題:你沒有爲你的表達做任何事情。因此,它的結果不會改變任何東西。在'(str(subs temp 0)( - (count temp)2))「}」)'你指的是'temp','temp =「{」'和'(count temp)'給你'1 '。所以你正在計算'(-1 2)'=>'-1'這是你的子串的第一個索引,這顯然不是你想要的。 – n2o

回答

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

+2

因爲你已經在使用解構和'for',所以表達'組合'的一種更清晰的方法是'(對於[數據],[數據]和[數據])。 – Thumbnail

相關問題