Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support constructing map from pairs #943

Closed
xiaq opened this issue Mar 21, 2020 · 1 comment
Closed

Support constructing map from pairs #943

xiaq opened this issue Mar 21, 2020 · 1 comment
Milestone

Comments

@xiaq
Copy link
Member

xiaq commented Mar 21, 2020

Transforming a map into a different one now requires mutating a map repeatedly. For example, to change all keys in a map to upper case:

use str
m = [&foo=1 &bar=2 &lorem=3]
new-m = [&]
for k [(keys $m)] {
  new-m[(str:to-upper $k)] = $m[$k]
}

If we have a function, say make-map, that takes pairs and puts a map (inputs can be supplied either via pipe or a list argument), the code becomes much simpler:

use str
m = [&foo=1 &bar=2 &lorem=3]
for k [(keys $m)] { put [(str:to-upper $k) $m[$k]] } | new-m = (make-map)
@xiaq xiaq added this to the 0.14 milestone Mar 21, 2020
@krader1961
Copy link
Contributor

For those wondering why this feature might be useful see the discussion about Elvish persistent data structures. In functional programming languages, such as Haskell, such data structures are central to the design of the language. They therefore use very sophisticated solutions to the problem of cheaply mutating otherwise immutable lists or maps. Elvish currently uses the simplest, and typically least performant, solution for that problem: copy on write. See https://en.wikipedia.org/wiki/Persistent_data_structure.

Note that the

    new-m[(str:to-upper $k)] = $m[$k]

in the first example in the problem description actually creates a new map and binds it to the new-m variable name. It does not mutate the existing map bound to new-m. Which, given the copy on write semantics, is why that pattern is inefficient and something like the proposed make-map command is useful.

@xiaq xiaq closed this as completed in 05156ea May 5, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants