https://github.com/pablobcb/clj-with
Macro inspired by Elixir's `with` statement
https://github.com/pablobcb/clj-with
clj clojure pattern-matching with
Last synced: 5 months ago
JSON representation
Macro inspired by Elixir's `with` statement
- Host: GitHub
- URL: https://github.com/pablobcb/clj-with
- Owner: pablobcb
- License: epl-1.0
- Created: 2018-05-18T03:55:56.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2019-05-13T16:39:28.000Z (over 6 years ago)
- Last Synced: 2025-03-23T20:37:12.268Z (11 months ago)
- Topics: clj, clojure, pattern-matching, with
- Language: Clojure
- Homepage:
- Size: 21.5 KB
- Stars: 4
- Watchers: 1
- Forks: 1
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README
# clj-with
Macro inspired by Elixir's `with` statement
[](https://clojars.org/clj-with)
Macro
Chain pattern matching clauses, using `clojure.core.match/match`. Takes a vector of
bindings to match, a body, and optionally an `:otherwise` keyword followed by list
of clauses to match in case of failure.
Pattern matches each bind and if all
clauses match, the body is executed returning its result. Otherwise the chain
is aborted and the non-matched value is matched against the optional :else
clauses, if provided. Raises `java.lang.IllegalArgumentException` if none
of the clauses match, just as `clojure.core.match/match`.
Example:
```clojure
(defn f1 [] [:ok 10 20])
(defn f2 [k] [:ok (inc k)])
(defn produce-error [] [:error :match-error])
(with [[:ok x y] (f1)
[:ok z] (f2 (+ x y))]
(do (println "all clauses have matched :)")
(* z 2))
:otherwise
[:error err] err
:else :no-match)
;=> 62
(with [[:ok x y] (f1)
[:ok z] (produce-error)]
(* z 2)
:otherwise
[:error err] err)
;=> :match-error
```
For more use cases peek at the `test` folder