prepend
Definition: | sequence s2 = prepend(object s1, object x) |
Description: |
Prepend x to the start of sequence s1. The length of s2 will be always be one more than length(s1), unless s1 is an atom, in which case the length of s2 will be 2. |
pwa/p2js: | Supported. |
Comments: |
If x is an atom this is the same as s2 = x & s1 .
If x is a sequence it is definitely not the same.
Although s1 is typically a sequence, and historically it had to be, it can now also be an atom, which can simplify certain algorithms. The extra storage is allocated automatically and very efficiently with Phix’s dynamic storage allocation. The case where s1 and s2 are the same variable (as in Example 1 below) is handled very efficiently. Avoid using string = prepend(string,char) on very long strings in performance critical code, if at all possible rework the code logic to use append. When working with a dword-sequence, prepend is just as fast as append. TIP: prepend() is ideally suited to adding an element (and always exactly one element) to a (sequence which represents a) list or table. When constructing strings, concatenation ('&') should be used instead - even though prepend() is technically valid in some character-by-character cases, concatenation makes the intent clearer. Also note that concatenation must be used when the intent is to add "zero, one, or more" elements (or characters) to a list or table (or string), in a single operation. |
Example 1: | You can use prepend() to dynamically grow a sequence, e.g. |
sequence x x = {} for i=1 to 10 do x = prepend(x, i) end for -- x is now {10,9,8,7,6,5,4,3,2,1} (or use tagset(1,10,-1), or reverse(tagset(10))) |
|
Example 2: | Any kind of Phix object can be prepended to a sequence, e.g. |
sequence x, y, z x = {"fred", "barney"} y = prepend(x, "wilma") -- y is now {"wilma", "fred", "barney"} z = prepend(prepend(y, "betty"), {"bam", "bam"}) -- z is now {{"bam", "bam"}, "betty", "wilma", "fred", "barney"} |
|
Example 3: | Watch out for this common mistake: |
prepend({3,4,5}, {1,2}) -- {{1,2}, 3, 4, 5} prepend("cde", "ab") -- {"ab",'c','d','e'} -- Compare with concatenation: {1,2} & {3,4,5} -- {1, 2, 3, 4, 5} "ab" & "cde" -- "abcde" |
|
Implementation: | via :%opApnd (used for both append and prepend) in builtins\VM\pApnd.e (an autoinclude) - be warned however it is low-level complicated stuff that you do not need to know. |
See Also: | append, concatenation operator &, sequence-formation operator, tagset, reverse |