Shukai Ni
Shukai Ni

Reputation: 467

Clojure String index out of range: -1

I am trying to convert a clojure map to a Mathematica Graph, the map relations is

{: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 []}

A function is defined as

 (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)) "}" ))
    )
  )

it supposed to give a string like

"{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}"

but it runs as CompilerException java.lang.StringIndexOutOfBoundsException: String index out of range: -1, compiling:(form-init2059367294355507639.clj:269:20)

the problem is I tested the code in (do &expr) line by line and they worked as expected, but when I put them in this function, I got an error.

Upvotes: 0

Views: 215

Answers (1)

n2o
n2o

Reputation: 6477

It seems that you are lacking some basics of Clojure, since you are using def-in-def. This is where you might should start with.

It might be a good idea to split your problem into smaller problems instead of putting it directly all together. Therefore, a first step would be to create the combinations, then convert them to your desired string combinations and in the last step create the complete string. This could look like this:

(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) "}")))

(Applied suggestions from the comments, thanks to @Thumbnail)

Please play around with the Clojure basics to really get started with the language. A good starting point surely is braveclojure.com

Upvotes: 3

Related Questions