lentes
lentes copied to clipboard
`nth` should support lists
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)
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}))))))