mirror of
https://github.com/janet-lang/janet
synced 2025-01-11 08:00:27 +00:00
Add put-in.
This commit is contained in:
parent
7a13d24e6f
commit
99f147219a
@ -961,14 +961,15 @@
|
|||||||
(or d dflt))
|
(or d dflt))
|
||||||
|
|
||||||
(defn update-in
|
(defn update-in
|
||||||
"Access a value in a nested data structure. Looks into the data structure via
|
"Update a value in a nested data structure by applying f to the current value.
|
||||||
|
Looks into the data structure via
|
||||||
a sequence of keys. Missing data structures will be replaced with tables. Returns
|
a sequence of keys. Missing data structures will be replaced with tables. Returns
|
||||||
the modified, original data structure."
|
the modified, original data structure."
|
||||||
[ds ks f & args]
|
[ds ks f & args]
|
||||||
(var d ds)
|
(var d ds)
|
||||||
(def len (length ks))
|
(def len-1 (- (length ks) 1))
|
||||||
(if (< len 1) (error "expected at least 1 key in ks"))
|
(if (< len-1 0) (error "expected at least 1 key in ks"))
|
||||||
(for i 0 (- len 1)
|
(for i 0 len-1
|
||||||
(def k (get ks i))
|
(def k (get ks i))
|
||||||
(def v (get d k))
|
(def v (get d k))
|
||||||
(if (= nil v)
|
(if (= nil v)
|
||||||
@ -976,11 +977,33 @@
|
|||||||
(put d k newv)
|
(put d k newv)
|
||||||
(set d newv))
|
(set d newv))
|
||||||
(set d v)))
|
(set d v)))
|
||||||
(def last-key (last ks))
|
(def last-key (get ks len-1))
|
||||||
(def last-val (get d last-key))
|
(def last-val (get d last-key))
|
||||||
(put d last-key (f last-val ;args))
|
(put d last-key (f last-val ;args))
|
||||||
ds)
|
ds)
|
||||||
|
|
||||||
|
(defn put-in
|
||||||
|
"Put a value into a nested data structure.
|
||||||
|
Looks into the data structure via
|
||||||
|
a sequence of keys. Missing data structures will be replaced with tables. Returns
|
||||||
|
the modified, original data structure."
|
||||||
|
[ds ks v]
|
||||||
|
(var d ds)
|
||||||
|
(def len-1 (- (length ks) 1))
|
||||||
|
(if (< len-1 0) (error "expected at least 1 key in ks"))
|
||||||
|
(for i 0 len-1
|
||||||
|
(def k (get ks i))
|
||||||
|
(def v (get d k))
|
||||||
|
(if (= nil v)
|
||||||
|
(let [newv (table)]
|
||||||
|
(put d k newv)
|
||||||
|
(set d newv))
|
||||||
|
(set d v)))
|
||||||
|
(def last-key (get ks len-1))
|
||||||
|
(def last-val (get d last-key))
|
||||||
|
(put d last-key v)
|
||||||
|
ds)
|
||||||
|
|
||||||
(defn update
|
(defn update
|
||||||
"Accepts a key argument and passes its associated value to a function.
|
"Accepts a key argument and passes its associated value to a function.
|
||||||
The key is the re-associated to the function's return value. Returns the updated
|
The key is the re-associated to the function's return value. Returns the updated
|
||||||
|
Loading…
Reference in New Issue
Block a user