Skip to content

cj-price/pipe.dream

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

21 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

pipe.dream

https://img.shields.io/clojars/v/pipe.dream.svg

Elixir-like pipe |> in Clojure(Script).

Usage

Simple example using the -> equivalent.

(ns example.core
  (:require [pipe.dream :refer [pipe]]))

(pipe
 {:x 1}
 |> update :x inc
 |> update :x str
 |> assoc :y "3")
;; => {:x "2", :y "3"}
 
(macroexpand-1 '(pipe
                 {:x 1}
                 |> update :x inc
                 |> update :x str
                 |> assoc :y "3"))
;; => (-> {:x 1} (update :x inc) (update :x str) (assoc :y "3"))

Simple example using the ->> equivalent.

(pipe
 (range 10)
 _> map inc
 _> reduce +)
;; => 55
 
(macroexpand-1 '(pipe
                 (range 10)
                 _> map inc
                 _> reduce +))
;; => (-> (range 10) (as-> X (map inc X)) (as-> X (reduce + X)))
 
;; Same as
(->> (range 10) (map inc) (reduce +))
;; => 55

Of course, you can mix them together into one pipe.

(pipe
 {:stuff (range 4)}
 |> :stuff
 _> map inc
 |> (fn [stuff] {:inc-stuff stuff}))
;; => {:inc-stuff (1 2 3 4)}

Advanced Usage

Listed above are some basic examples of how to use the pipe macro. defpipe is also another macro provided that can be used in place of defn.

So this:

(defn inc-twice [n]
  (pipe
   n
   |> inc
   |> inc))

Can be represented as:

(defpipe inc-twice
  |> inc
  |> inc)

(inc-twice 1)
;; => 3

Included with defpipe are some optional arguments that may be of some use. To include any of these, supply the argument pair after the name of the pipe and before the pipe chain.

:arg

Provides the argument to the function instead of expecting an argument provided by the caller.

(defipe inc-twice
  :arg 1
  |> inc
  |> inc)

(inc-twice)
;; => 3

:let

Top level let in the case of destructuring.

(defpipe inc-twice
  :let {:keys [n]}
  |> constantly n
  |> inc
  |> inc)

(inc-twice {:n 4})
;; => 6

Multi-arity pipes are also a thing.

(defipe add-stuff
  :let [v1 v2 v3]
  :arg v1
  |> + v2 v3)

(add-stuff 1 2 3)
;; => 6

:doc

Adds a doc string to the underlying defn.

For more examples, view the tests in the test/pipe/dream/test.cljc file.

Require

Say you’re running a linter like clj-kondo and it’s telling you that there is an unresolved symbol. You can fix this by using :refer in the ns :require. Doing this in Clojure and ClojureScript is a bit different. Below demonstrates how you’d do it in each language.

Clojure

(ns example.core
  (:require [pipe.dream
             :refer [defpipe pipe |> _>]]))

ClojureScript

(ns example.core
  (:require [pipe.dream
             :refer [|> _>]
             :refer-macros [defpipe pipe]))

About

Elixir-like pipe `|>` in Clojure(Script).

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published