Add a new "conj" command for appending values to a list.

This commit is contained in:
Qi Xiao 2023-01-04 18:56:00 +00:00
parent 24640d3241
commit 0b0f5ba867
4 changed files with 37 additions and 0 deletions

View File

@ -5,6 +5,9 @@ This is the draft release notes for 0.19.0, scheduled to be released around
- A new `doc` module provides access to the documentation of builtin modules.
- A new `conj` command "appends" values to a list, and has a guaranteed time
complexity independent of the size of the list.
- A new `inexact-num` converts its argument to an inexact number.
It is functionally identical to the now deprecated `float64` command since

View File

@ -31,6 +31,23 @@ fn ns {|map| }
# ```
fn make-map {|input?| }
# Outputs a list created from adding values in `$more` to the end of `$list`.
#
# The output is the same as `[$@list $more...]`, but the time complexity is
# guaranteed to be O(m), where m is the number of values in `$more`.
#
# Examples:
#
# ```elvish-transcript
# ~> conj [] a
# ▶ [a]
# ~> conj [a b] c d
# ▶ [a b c d]
# ```
#
# Etymology: [Clojure](https://clojuredocs.org/clojure.core/conj).
fn conj {|list @more| }
# Output a slightly modified version of `$container`, such that its value at `$k`
# is `$v`. Applies to both lists and to maps.
#

View File

@ -17,6 +17,7 @@ func init() {
"make-map": makeMap,
"conj": conj,
"assoc": assoc,
"dissoc": dissoc,
@ -74,6 +75,13 @@ func makeMap(input Inputs) (vals.Map, error) {
return m, errMakeMap
}
func conj(li vals.List, more ...any) vals.List {
for _, val := range more {
li = li.Conj(val)
}
return li
}
func assoc(a, k, v any) (any, error) {
return vals.Assoc(a, k, v)
}

View File

@ -41,6 +41,15 @@ func TestMakeMap(t *testing.T) {
)
}
func TestConj(t *testing.T) {
Test(t,
That("conj [] a").Puts(vals.MakeList("a")),
That("conj [a b]").Puts(vals.MakeList("a", "b")),
That("conj [a b] c").Puts(vals.MakeList("a", "b", "c")),
That("conj [a b] c d").Puts(vals.MakeList("a", "b", "c", "d")),
)
}
func TestAssoc(t *testing.T) {
Test(t,
That(`put (assoc [0] 0 zero)[0]`).Puts("zero"),