Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

nth should support lists #10

Open
metametadata opened this issue Mar 21, 2018 · 1 comment
Open

nth should support lists #10

metametadata opened this issue Mar 21, 2018 · 1 comment

Comments

@metametadata
Copy link

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 metametadata changed the title l/key should support lists l/nth should support lists Mar 21, 2018
@metametadata metametadata changed the title l/nth should support lists nth should support lists Mar 21, 2018
@aiba
Copy link
Collaborator

aiba commented Sep 5, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants