Can I get this variable in def?

Is there a way to mimic a variable thisin something like (def foo {:two 2 :three (inc (:two this))})? Something like that would be even better (def foo {:two 2 :three (inc ::two)}). I was told that there is a library that does just that, but I cannot find anything like it.

Thank!

+3
source share
2 answers

(Update: rebuilt and redesigned. build-mapAnd (sketch) -m>macros added.)

This specific example can be written as

(def foo (zipmap [:two :three] (iterate inc 2)))

The simplest general solution that is happening to me at the moment:

user> (-> {} (assoc :two 2) (#(assoc % :three (inc (:two %)))))
{:three 3, :two 2}

It is actually very flexible, although you need to write out multiple times assoc.

To include syntax similar to the syntax from the question text, you can use something like this:

(defn build-map* [& kvs]
  (reduce (fn [m [k v]]
            (assoc m k (v m)))
          {}
          kvs))

(defmacro build-map [& raw-kvs]
  (assert (even? (count raw-kvs)))
  (let [kvs (map (fn [[k v]] [k `(fn [m#] (let [~'this m#] ~v))])
                 (partition 2 raw-kvs))]
    `(build-map* ~@kvs)))

user> (build-map :two 2 :three (inc (:two this)))
{:three 3, :two 2}

, , this. %, . , , -m> ( ),

(-m> {} :two 2 :three (inc (:two %)))

.


( ):

;;; from Alex Osborne debug-repl,
;;; see http://gist.github.com/252421
;;; now changed to use &env
(defmacro local-bindings
  "Produces a map of the names of local bindings to their values."
  []
  (let [symbols (map key &env)]
    (zipmap (map (fn [sym] `(quote ~sym)) symbols) symbols)))

(let [two 2
      three (inc two)]
  (into {} (map (fn [[k v]] [(keyword k) v]) (local-bindings))))
{:two 2, :three 3}

, , let...

+2

-, let.

(def foo (let [x {:two 2}]
           (assoc x :three (inc (:two x)))))

, , . - " ", ->, , - . . . , , , . let - . . Rich:

(let [x []
      x (conj x 1)
      x (into x [2 3])
      x (map inc x)]
...) 
+4

Source: https://habr.com/ru/post/1733590/


All Articles