lentes icon indicating copy to clipboard operation
lentes copied to clipboard

`nth` should support lists

Open metametadata opened this issue 7 years ago • 1 comments

This would be convenient because often parts of bigger data end up being lists after applying core functions (e.g. map).

Steps:

(require '[lentes.core :as l])
(let [data (list 0 1 2 3)
      lense (l/nth 2)]
  (println "A ->" (l/focus lense data))
  (l/over lense inc data)
  (println "B ->" (l/focus lense data)))

Expected:

A -> 2
B -> 3

Actual:

1 -> 2
Uncaught Error: No protocol method IAssociative.-assoc defined for type cljs.core/List: (0 1 2 3)

metametadata avatar Mar 21 '18 18:03 metametadata

Agreed. I'll work on updating lentes.core/nth, but here is a draft implementation in the meantime.

(defn nth [idx]
  (l/lens
   (fn [s]
     (c/nth s idx))
   (fn [s f]
     (cond
       (vector? s) (update s idx f)
       (sequential? s) (map-indexed (fn [i x]
                                      (if (= i idx)
                                        (f x)
                                        x))
                                    s)
       :else (throw (ex-info "nth not supported" {:value s}))))))

aiba avatar Sep 05 '24 02:09 aiba