Logo

Programming-Idioms

History of Idiom 44 > diff from v19 to v20

Edit summary for version 20 by :

Version 19

2015-09-04, 18:04:29

Version 20

2015-10-29, 14:05:14

Idiom #44 Insert element in list

Insert element x at position i in list s. Further elements must be shifted to the right.

Idiom #44 Insert element in list

Insert element x at position i in list s. Further elements must be shifted to the right.

Code
take i s ++ x : drop i s
Code
take i s ++ x : drop i s
Code
s.insert(i, x);
Code
s.insert(i, x);
Doc URL
http://doc.rust-lang.org/std/vec/struct.Vec.html#method.insert
Doc URL
http://doc.rust-lang.org/std/vec/struct.Vec.html#method.insert
Demo URL
http://is.gd/70EXU4
Demo URL
http://is.gd/70EXU4
Code
s.splice(i, 0, x);
Code
s.splice(i, 0, x);
Code
splice(@s, $i, 0, $x)
Code
splice(@s, $i, 0, $x)
Comments bubble
The 0 tells splice we're replacing zero elements with $x at position $i--resulting in an insertion, rather than replacement.
Comments bubble
The 0 tells splice we're replacing zero elements with $x at position $i--resulting in an insertion, rather than replacement.
Imports
import java.util.List;
Imports
import java.util.List;
Code
s.add(i, x);
Code
s.add(i, x);
Doc URL
http://docs.oracle.com/javase/7/docs/api/java/util/List.html#add%28int,%20E%29
Doc URL
http://docs.oracle.com/javase/7/docs/api/java/util/List.html#add%28int,%20E%29
Code
s = append(s, 0)
copy(s[i+1:], s[i:])
s[i] = x
Code
s = append(s, 0)
copy(s[i+1:], s[i:])
s[i] = x
Comments bubble
Extend slice by 1 (it may trigger a copy of the underlying array).
Then shift elements to the right.
Then set s[i].
Comments bubble
Extend slice by 1 (it may trigger a copy of the underlying array).
Then shift elements to the right.
Then set s[i].
Origin
https://code.google.com/p/go-wiki/wiki/SliceTricks
Origin
https://code.google.com/p/go-wiki/wiki/SliceTricks
Demo URL
http://play.golang.org/p/p2MRxxkyq1
Demo URL
http://play.golang.org/p/p2MRxxkyq1