LoginSignup
4
4

More than 5 years have passed since last update.

Clojureの標準にないけど欲しい関数

Posted at

って結構ありませんか?
よく使ったり使わなかったりする汎用的に使える関数がこちら

(defn third [coll] (second (next coll)))

secondがあるならthirdもほしい
thirdぐらいまでは結構使いませんかねえ?

(defmacro def-nth* [index]
  `(defn ~(symbol (str "nth" index))
     ([coll#] (nth coll# ~index))
     ([coll# not-found#] (nth coll# ~index not-found#))))
(doseq [i (range 10)] (eval (list 'def-nth* i)))

あんまり使わないけど、nth0nth9までの関数を↑で定義して使える

(defn ->int [x] (Integer/parseInt x))
(defn ->long [x] (Long/parseLong x))
(defn ->double [x] (Double/parseDouble x))

何回も定義してる気がする。めんどいから標準でほしい

(defn indexed [coll] (map vector (range) coll))
(defn some-indexed [f coll]
  (->> (keep-indexed f coll)
       (filter identity)
       first))

some-indexedは結構使う機会多い気がします。

(defn cons-last [x coll] (concat coll [x]))

リストの最後に追加するやつ標準になんでないんでしょうか?

(defn drop-nth [n coll]
  (mapcat butlast (partition-all n (cons-last nil coll))))

最近使ったけどあまり使わないかな。take-nthのdrop版

(defn nth-select [coll indices]
  (map #(nth coll %) indices))

リストの中のほしい番号の分だけ取り出す。
リストに対するindexに基づいたアクセスはvectorにすれば結構いける関数多い(update-inなど)ですがselect-keysはマップになってしまうので仕方なく定義しとく

他にもこういうの使うよとか、こっち使えばいいよとかあれば教えてほしい・・・

4
4
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4