velcro icon indicating copy to clipboard operation
velcro copied to clipboard

Spread map values

Open peterjoel opened this issue 4 years ago • 4 comments

Currently .. is supported in maps for keys, but not values. It would be nice to be able to do this:

let map = hash_map! { 
    ..(0..5): ..(10..)
}

Which would give the same result as:

let map = (0..5).into_iter().zip(10..).collect::<HashMap<_, _>>();

May need to consider if it is an error if the number of keys exceeds number of values or vice versa.

It doesn't really make sense to spread values when the key is not also spread, so this should be an error:

let map = hash_map! { 
    0: ..(10..)
}

peterjoel avatar Dec 09 '20 12:12 peterjoel

Hi, I'm wondering if this is a common enough use case to warrant the (a) internal complexity; (b) maintenance; and (c) cognitive/documentation aspect.

xpe avatar Dec 21 '20 04:12 xpe

It would not add significant complexity in the parsing. But yes, it could make the generated code more complicated (and potentially slow) if we decided to do checks to make sure the keys and values are the same length.

If we forgo the length check, and behave exactly like the zip example given above, then the generated code will be relatively simple. I think it really comes down to whether it is least surprising to a user if the following panics or truncates the values:

let map = hash_map! { 
    ..(0..5): ..(0..2)
}

I'm inclined towards just truncating the values, as would happen with manually doing a zip and collect. The reason being that in the general case (where the inputs are arbitrary impls of IntoIterator) it is impossible to detect the bounds of an iterator until you actually finish iterating it.

peterjoel avatar Dec 21 '20 11:12 peterjoel

As for documentation, there is still a lot of work to be done there. But I think it could actually simplify docs because we can say that .. can be used everywhere that a value can be. As it is, map values are the exception to a rule.

peterjoel avatar Dec 21 '20 11:12 peterjoel

After getting some 'familiarity' with how velcro uses .. (via #10), I see why this feature (spreading map values) is a logical next step with the syntax.

xpe avatar Dec 25 '20 17:12 xpe