umka-lang icon indicating copy to clipboard operation
umka-lang copied to clipboard

insert() for inserting in the middle of an array

Open ske2004 opened this issue 3 years ago • 4 comments

This is needed often when I maintain a sorted array and need to keep the ordering correct.

ske2004 avatar Jul 11 '22 15:07 ske2004

@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.

vtereshkov avatar Jul 11 '22 15:07 vtereshkov

hmm seems quite more cumbersome (for a scripting language at least)

ske2004 avatar Jul 11 '22 15:07 ske2004

although it's not such a big deal because i need it only in handful of places

ske2004 avatar Jul 11 '22 15:07 ske2004

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

vtereshkov avatar Jul 11 '22 16:07 vtereshkov

Thank you. Just in time as I was going to need it :P

ske2004 avatar Aug 29 '22 07:08 ske2004