janet-lang / spork

Various Janet utility modules - the official "Contrib" library.
MIT License
124 stars 36 forks source link

assoc? Adding a few more functional operators #108

Open Inc0n opened 1 year ago

Inc0n commented 1 year ago

Assoc and assoc-in are analogous to put and put-in without the side effects.

There is first which is sometimes more convenient than (map (fn [x] (x 0)) xs). However, there isn't a second so we have (map first xs) and(map (fn [x] (x 1)) xs)`.

There may be more of them that could be useful for FP that I haven't thought of ATM.

Would it be a good idea to add them as part of spork?

eko234 commented 2 months ago

Hello, rn I'm indeed playing with that idea, I don't know if its the best way to do it, but by design it is not going to be performant anyway :V

(defn assoc [ds k v & ekvs]
  (cond
   (struct? ds) (struct ;(kvs ds) k v ;ekvs)
   (and (tuple? ds) (empty? ekvs) (number? k))
   (if (= k (length ds))
     (tuple ;ds v)
     (tuple ;(slice ds 0 k) v ;(slice ds (inc k) (length ds))))
   (error "ds must be a struct or a tuple and tuples' keys must be numbers, also tuples do'nt accept extra kv's")))

(defn assoc-in [ds [k & ks] v]
  (if (empty? ks)
    (assoc ds k v)
    (assoc ds k (assoc-in (get ds k {}) ks v))))

AFIK it works as in clojure, it is something trivial enough so people can add it to their projects by themselves, but I think it would be nice to have it at hand with spork