Skip to content

Commit 89bedcd

Browse files
authored
Add apply-template function to basilisp.core.template (#516)
1 parent 4674364 commit 89bedcd

File tree

2 files changed

+24
-11
lines changed

2 files changed

+24
-11
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1616
* Added context information to the `CompilerException` string output (#493)
1717
* Added Array (Python list) functions (#504, #509)
1818
* Added shell function in `basilisp.shell` namespace (#515)
19+
* Added `apply-template` function to `basilisp.core.template` namespace (#516)
1920

2021
### Changed
2122
* Change the default user namespace to `basilisp.user` (#466)

src/basilisp/core/template.lpy

Lines changed: 23 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,27 @@
22
(:require
33
[basilisp.walk :refer [postwalk-replace]]))
44

5+
(defn apply-template
6+
"Given a template expression `expr` and bindings (as `argv`), replace all instances
7+
of elements from `argv` in `expr` with the corresponding elements from `values`.
8+
9+
For example:
10+
11+
(apply-template '[x y] '(= x y) '[1 2])
12+
13+
produces
14+
15+
(= 1 2)"
16+
[argv expr values]
17+
(as-> values $
18+
(interleave argv $)
19+
(apply hash-map $)
20+
(postwalk-replace $ expr)))
21+
522
(defmacro do-template
6-
"Given a template expression expr and bindings, produce a do expression with
7-
the repeated templated expressions replacing names in argv with elements from
8-
args.
23+
"Given a template expression `expr` and bindings, produce a `do` expression with
24+
the repeated templated expressions replacing names in `argv` with elements from
25+
`args`.
926

1027
For example:
1128

@@ -19,12 +36,7 @@
1936
(= 1 (dec 2))
2037
(= 2 (inc 1)))"
2138
[argv expr & args]
22-
(let [n (count argv)
23-
arg-groups (partition n args)
24-
template-expr (fn [arg-group]
25-
(as-> arg-group $
26-
(interleave argv $)
27-
(apply hash-map $)
28-
(postwalk-replace $ expr)))]
39+
(let [n (count argv)
40+
arg-groups (partition n args)]
2941
`(do
30-
~@(map template-expr arg-groups))) )
42+
~@(map #(apply-template argv expr %) arg-groups))))

0 commit comments

Comments
 (0)