1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Clojureでmapcatのfor版としてforcatを作る(+おまけpapply)

1
Posted at

なにげに便利なmapcatですが、そのfor版もなにげに便利だと思いますので作ってみます。

forcat.clj
(defmacro forcat [seq-exprs & body-exprs]
  `(apply concat (for ~seq-exprs (concat ~@body-exprs))))

body部に複数フォーム入れられるようにもしてみました。

user=> (forcat [x (range 3) y [:a :b]] [x] [y])
(0 :a 0 :b 1 :a 1 :b 2 :a 2 :b)

おまけ

短かったので全く別のこととしてpartial applyの単なるエイリアスとしてpapplyを作ってみます。

papply.clj
(defn papply [f & args] (apply partial apply f args))

これをどんなときに使うかですが、(map #(* %1 %2) [[3 5] [6 9]])のような動かないコードを改善するとき(map (fn [[v1 v2]] (* v1 v2)) [[3 5] [6 9]])とする代わりに(map (papply #(* %1 %2)) [[3 5] [6 9]])とすることができます。

1
1
0

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?