umka-lang
umka-lang copied to clipboard
insert() for inserting in the middle of an array
This is needed often when I maintain a sorted array and need to keep the ordering correct.
@skejeton As a workaround, you can now use append():
type T = int
fn insert(a: []T, i: int, v: T): []T {
return append(append(slice(a, 0, i), v), slice(a, i))
}
fn main() {
a := []int{1, 3, 4, 5}
b := insert(a, 1, 2)
printf(repr(a) + repr(b) + '\n') // { 1 3 4 5 } { 1 2 3 4 5 }
}
Go also encourages this idiom.
hmm seems quite more cumbersome (for a scripting language at least)
although it's not such a big deal because i need it only in handful of places
Another implementation with just one append():
fn insert(a: []T, i: int, v: T): []T {
if i == len(a) {
return append(a, v)
}
b := append(slice(a, 0, i + 1), slice(a, i))
b[i] = v
return b
}
Borrowed from here: https://stackoverflow.com/questions/46128016/insert-a-value-in-a-slice-at-a-given-index
Thank you. Just in time as I was going to need it :P