Using Built-In Sequence Functions

Back to tips page

By: mattlewis

There are a lot of new ways to do things with Euphoria 4, but some that I don't think have gotten enough attention are the new built in sequence routines:

In euphoria 3, we have to use lots of slices to manipulate a sequence. Suppose we needed to remove the fourth element from a sequence:

    -- the old way: 
    sequence foo = { 1, 2, 3, 3, 4, 5 } 
    foo = foo[1..3] & foo[5..6] 
    -- use remove(): 
    sequence bar = { 1, 2, 3, 3, 4, 5 } 
    bar = remove( bar, 4 ) 

The old way uses two slices. This means that two sequences must be allocated and their values copied before joining them together, which requires a third allocation and copy.

When using remove(), on the other hand, euphoria has been optimized to do as little work as possible. In this case, for instance, we're removing an element from bar, and assigning the result back to bar. In this case, euphoria is free to make changes directly to bar without needing any temps. So it moves the elements after the removal up in the sequence, updates the length of the sequence and is done.

The other built in sequence routines do similar things. For instance:

    sequence fox = "The brown fox" 
    fox = fox[1..4] & "quick " & fox[5..$] 
    sequence now = "Now time" 
    now = splice( now, "is the ", 5 ) 

It's also important to note that these built in functions do not have the normal overhead associated with normal, user created functions (i.e., no call stack, private variables, etc). They're really no different than any other built in operation, like addition, as far as overhead goes. I say this because I know there are some people overly obsessed with speed and premature optimization (you know who you are!) who would probably worry about this.


Quick Links

User menu

Not signed in.

Misc Menu