Use of for macro can cause timeout #211

Open
glchapman opened this Issue Mar 23, 2012 · 0 comments

1 participant

@glchapman

I'm not sure if this is a bug or a sandbox limitation, but I thought it should be noted as an issue. I kept getting timeouts with a working solution for problem 150. After looking through the various transformations performed by 4clojure and clojail, I found clojail's dotify. It turns out the for macro (at least in 1.3) uses .nth. Since it seemed the dotify transformation might be the problem, I replaced the for loop with a call to the map function and the solution worked without timing out.

Below is the non-working version. The only difference in the woking version is replacing the for macro on line 11 with: (map #(+ outer (* 10 %)) (gen (- power 2) (rest ds)))

(fn palindromes [min]
  (let [smin (str min)
        init-power (dec (count smin))
        pals
          (fn [outer-power]
            (letfn [(gen [power ds] (lazy-seq
                      (let [shell #(+ % (apply * % (repeat power 10)))
                            expand 
                              (fn [d]
                                (let [outer (shell d)]
                                  (for [n (gen (- power 2) (rest ds))]
                                    (+ outer (* 10 n))
                                  )))
                        ]
                        (cond
                          (zero? power) (range 10)
                          (= power 1) (range (if (= outer-power 1) 11 0) 100 11)
                          :else 
                            (let [mind (if (= power outer-power) 1 0)
                                  d (if-let [dc (first ds)]
                                      (max mind (- (int dc) (int \0)))
                                      mind)]
                              (mapcat expand (range d 10)))
                        ))))
              ]
              (gen outer-power (when (= outer-power init-power) smin))
            ))
        sq (if (zero? init-power)
             (mapcat pals (range))
             (mapcat pals (iterate inc init-power)))
    ]
    (drop-while #(< % min) sq)
  ))
@riksa riksa added a commit to riksa/fourclojure that referenced this issue Apr 5, 2015
@riksa riksa Problem 152: replaced "for" loop with a mapcat-map to work around ext…
…remely slow for execution in clojail used by 4clojure.com 4clojure/4clojure#66 and 4clojure/4clojure#211). removed profiling.
7cc7f2c
@craig-ludington craig-ludington added a commit to craig-ludington/fourclojure that referenced this issue Nov 7, 2015
@craig-ludington craig-ludington latin-square-slicing -- deprecate for macro 17eb076
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment