FiraCode/clojure/fira_code/coll.clj

29 wiersze
1011 B
Clojure
Czysty Zwykły widok Historia

2023-04-02 13:27:16 +00:00
(ns fira-code.coll
(:require
[clojure.string :as str]))
2020-03-23 23:37:50 +00:00
(defn index-of [pred xs]
2023-04-02 13:27:16 +00:00
"Returns the index of the first element in xs that satisfies the predicate pred,
or nil if no such element is found."
2020-03-23 23:37:50 +00:00
(let [res (reduce (fn [i x] (if (pred x) (reduced i) (inc i))) 0 xs)]
(if (>= res (count xs))
2023-04-02 13:27:16 +00:00
nil
res)))
2020-03-23 23:37:50 +00:00
(defn group-by-to [key-fn value-fn xs]
2023-04-02 13:27:16 +00:00
"Groups the elements in xs by applying the key function key-fn to each element,
and applies the value function value-fn to the resulting groups.
Returns a map of the form {k (value-fn vs)} where k is the result of applying
key-fn to a group of elements vs."
(->> xs
(group-by key-fn)
(reduce-kv (fn [m k vs]
(assoc m k (value-fn vs))))))
2020-05-15 01:51:54 +00:00
(defn multimap-by [f & kvs]
2023-04-02 13:27:16 +00:00
"Constructs a multimap by repeatedly applying the function f to a sequence of
key-value pairs. Returns a map where each key can have multiple values."
(reduce (fn [m [k v]]
(update m k f v))
{} kvs))