List Primitives

Summary
List Primitives
Macros
carRetrieve the first list element.
cdrRetrieve all secondary list elements.
command_listRetrieve list of built-in and active macros.
delete_nthRemove one or more elements from a list.
file_globReturn names of files that match patterns.
get_nthRetrieve a list element.
length_of_listDetermine list element count.
listDeclare a list symbol.
list_eachIterator though the list elements.
list_extractExtract list elements.
list_resetReset the list iterator.
make_listBuild an evaluated list.
nthExtract the indexed list item.
popPop the last element.
pushAdd an element onto a list.
put_nthModify a list element.
quote_listBuild an unevaluated list.
search_listSearch list contents.
shiftShift the first list element.
sort_listSort list.
spliceSplice a list, removing and/or adding elements.
strlenString length.
strnlenString length limited to an explicit maximum.
unshiftShift the first list element.

Macros

car

declare car(list lst)

Retrieve the first list element.

Description

The car() primitive retrieves a copy of the first element (also known as an atom) in the list lst; effectively removing all elements after the first.

car is non-destructive.  It does not remove any elements from the source list only returning a copy of what is the first element, as such the source list is unchanged.

Note:

As lists may contain any data type, it is advised to assigned the result to a polymorphic variable, so that its type can be ascertained.

Example

TODO

Returns

The car() primitive returns value of the first element from the source.

Like cdr, the car primitive is built on their Lisp counter parts, which are also non-destructive; that is, neither modify or change lists to which they are applied.

Portability

n/a

See Also

cdr, nth, put_nth, splice, list, pop, push

cdr

list cdr(list lst)

Retrieve all secondary list elements.

Description

The cdr() primitive retrieves a copy of everything but the first element (also known as an atom) in the list lst; effectively removing the first element.

cdr is non-destructive.  It does not remove any elements from the source list only returning a copy of what are the second and subsequent elements, as such the source list is unchanged.

Note:

The primitives car and cdr can be utilised to manipulate all elements on a list.  However, it is more efficient to use nth, pop, splice to extract individual elements, since internally it avoids having to copy sub-lists.

Example

TODO

Returns

The cdr() primitive returns a list containing the second and subsequent elements from the source.

Like car, the cdr primitive is built on their Lisp counter parts, which also non-destructive; that is, neither modify or change lists to which they are applied.

Portability

n/a

See Also

car, nth, put_nth, splice, list, pop, push

command_list

list command_list(  [int nomacros = FALSE],
[string pattern])

Retrieve list of built-in and active macros.

Description

The command_list() primitive returns a sorted list of all built-in primitives and the optionally all currently defined macros.

If nomacros is non-zero only built-in primitives are retrieved. otherwise the list includes all macros and command primitives.

The optional pattern is a regular expression similar to that accepted by the command line shells (See: file_match), providing an inclusion filter.

Parameters

nomacrosOptional boolean value, if stated as true then only built-ins primitives are retrieved, filtering any run-time loaded macros.
patternOptional string value containing the macro-name pattern to be applied against each name, only returning the matching.  A macro-name expression is a shell style regular expression (See: file_match) (e.g.  * for wildcard, ? for wild-character, and [..] to select a range of characters).

Returns

The command_list() primitive returns a list of strings each containing the name of a primitive or macro.

Portability

n/a

See Also

macro_list, file_match

delete_nth

void delete_nth(list lst,
  [int offset = 0],
 [int length = 1])

Remove one or more elements from a list.

Description

The delete_nth() primitive deletes length elements from the specified list lst starting at the index offset.

Parameters

lstList reference which shall have elements removed.
offsetOptional integer offset within list, if omitted defaults to the first element being offset 0.
lengthOptional integer length, states the number of elements to be removed; if omitted only one element is removed.  If 0 or less, than no elements will be removed.

Returns

nothing

Portability

n/a

See Also

get_nth, nth, splice

file_glob

list file_glob(string files)

Return names of files that match patterns.

Description

The file_glob() primitive performs file name globbing in a fashion similar to the csh shell.  It returns a list of the files whose names match any of the pattern arguments.

No particular order is guaranteed in the list, so if a sorted list is required the caller should use sort_list.

The pattern arguments may contain any of the following special characters:

~[user/]Home directory of either the current or the specified user.
?Matches any single character.
*Matches any sequence of zero or more characters.
[ch]Matches any single character in chars.  If ch’s contains a sequence of the form a-b then any character between a and b (inclusive) will match.
\xMatches the character x.

Returns

The file_glob() primitive returns a list of strings corresponding to the filenames which match the wild card expression in string.  When no matches or error, an empty list is returned.

See Also

glob, file_canon, file_pattern, find_file, expandpath

get_nth

declare get_nth(int idx,
list expr)

Retrieve a list element.

Description

The get_nth() primitive retrieves the element positioned at offset idx within the specified list expression expr.

Note:

This primitive is generally not utilised directly as the GRIEF language supports list offset operator of the form [idx].

Returns

The get_nth() primitive returns the value of the referenced element, otherwise NULL if the index is out of bounds.

Portability

n/a

See Also

car, cdr, nth, put_nth, splice, list, pop, push

length_of_list

int length_of_list(list lst)

Determine list element count.

Description

The length_of_list() primitive retrieves the number of top-level elements (atoms) within the list lst; with sub-lists being counted as single elements.

Returns

The length_of_list() primitive returns the top-level element count.

Portability

n/a

See Also

make_list, quote_list, list_each, list_extract

list

list sym1, sym2 ...;

Declare a list symbol.

Description

The list statement declares a list being a container of atoms.  More precisely, a list is either an empty container NULL, or a sequential list of values.

A list can store any other data type, including lists, allowing the creation of complex types.  A list may generally only be extended at its end, by appending data; elements can be updated using put_nth and replaced using splice.

Any element may be referenced by specifying its ordinal position in the list using <get_th> and array subscripts.  Lists are not the most efficient data types, since subscript element access involves iterating from the head until the associated value is referenced, whereas list_each primitive allows effective iteration.

Returns

nothing

Portability

n/a

See Also

Types, int, string, float, double, array

list_each

int list_each(list lst,
 declare &value,
 [int increment = 1])

Iterator though the list elements.

Description

The list_each() primitive iterates over a normal list value and sets the variable value to be each element of the list in turn.

Example

Split the flag list specification spec into its components and iterator the results.

const list flags = split(spec, ",");
string flag;

while (list_each(flags, flag) >= 0) {
process_flag(flag);
}

Warning:

If any part of the list is modified, foreach may become very confused.  Adding or removing elements within the loop body, for example with splice shall result in unpredictable results possibility crashing the editor.

Secondary list iteration continues until the last element within the list is consumed; if the loop is terminated prior to the end condition, list_reset should be used to reset the list cursor for subsequent iterations.

Parameters

lstList expression.
valueVariable populated with the element value.
incrementOptional integer iterator loop increment, if omitted defaults to one element.

Returns

The list_each() primitive returns the element index retrieved, otherwise -1 upon an end-of-list condition or error.

Portability

A GriefEdit extension.

See Also

make_list, quote_list, length_of_list, list_reset, list_extract

list_extract

list list_extract(list lst,
 int start,
 [int end],
 [int increment])

Extract list elements.

Description

The list_extract() primitive iterates over the list values generating a new list of the referenced elements within the list.

Parameters

lstList expression.
startOptional integer index, if specified states the first element index at which the iterations begins.  When omitted the iterations begins from the start of the list.
endOptional integer index, if specified states the last element index at which the iterations terminates.  When omitted the iterations completes at the end of the list.
incrementOptional integer iterator loop increment, if omitted defaults to one element.

Returns

The list_extract() primitive returns a list containing the referenced elements, otherwise a NULL list on error.

Portability

n/a

See Also

make_list, quote_list, length_of_list, list_each

list_reset

int list_reset(list lst)

Reset the list iterator.

Description

The list_reset() primitive resets the list iteration cursor.

Parameters

lstList expression.

Returns

The list_reset() primitive returns the selected element index.

Portability

A GriefEdit extension.

See Also

make_list, quote_list, length_of_list, list_each, list_extract

make_list

list make_list(...)

Build an evaluated list.

Description

The make_list() primitive builds a new list constructed from the specified arguments.  Each of the specified arguments shall be evaluated and appended the end of the list.  This is in contrast to the quote_list primitive which does not evaluate any of the arguments.

Parameters

...One or more values to be made into list elements.

Returns

The make_list() primitive returns the built list.

Portability

n/a

See Also

quote_list, length_of_list, list_each, list_extract

nth

declare nth(list expr,
int idx,
 [int idx2 ...])

Extract the indexed list item.

Description

The nth() primitive retrieves the value of the referenced list element at the index idx from the list expression expr.  The first element of a list is element 0; the nth primitive allows lists to be treated like arrays.  The last element of a list is length_of_list minus one.

The nth() primitive is an efficient way of accessing random elements within a list, than for example using the lists primitive car and cdr.  In addition nth can access access multidimensional lists as a single operation.

Note:

This primitive is the underlying implementation of the list offset operator [], which are converted by the GRIEF Macro Compiler.

Furthermore, this interface should be considered as an internal primitive.  As this primitive is not compatible with the nth macro of CRiSP ™ its direct usage is not recommended, instead rely on the offset operator [].

Parameters

exprList expression.
idxInteger index.
...None or more integer indexs of sub-elements.

Returns

The nth() primitive returns the value of the specified element from the referenced list, otherwise NULL on error.

Portability

GRIEF uses an alternative prototype to support support multidimensional lists, unlike CRiSP ™ which only supports a single dimension.

nth(expr, list_expr)

As such for portability nth use should be restricted.

See Also

car, cdr, put_nth, splice, list, pop, push

pop

declare pop(list expr)

Pop the last element.

Description

The pop() primitive removes and returns the last value of the list, shortening the list by one element.

Returns

The pop() primitive returns the element removed, otherwise NULL on error.

Example

Iterator the list from the end, removing and then printing each element in the process;

list l = {"one", "two", "three", "four"};

while (length_of_list(l)) {
message("%s", pop(l));
}

the resulting output

four
three
two
one

Portability

A GriefEdit extension

See Also

push, shift, splice, car, cdr

push

declare push(list lst,
declare value ...)

Add an element onto a list.

Description

The push() primitive adds one or more elements value to the end of the list.

Returns

The push() primitive returns a copy of the value added.

Portability

A GriefEdit extension.

See Also

pop, shift, splice, car, cdr

put_nth

declare put_nth(symbol,
...)

Modify a list element.

Description

The put_nth() primitive modifies the element within the specified list.

Note:

This primitive is generally not utilised directly as the GRIEF language supports a list offset operator of the form [idx].

Returns

The put_nth() primitive returns the value of the referenced element, otherwise NULL if the index is out of bounds.

Portability

Standard CRiSP ™ implementation utilises an alternative prototype which does not support multidimensional lists.

put_nth(expr, list_expr, value)

As such for portability put_nth use should be restricted.

See Also

car, cdr, nth, get_nth, splice, list, pop, push

quote_list

list quote_list(...)

Build an unevaluated list.

Description

The quote_list() primitive builds a list of the specified arguments unchanged and unevaluated.  This is in contrast to the make_list primitive which shall evaluate which of the arguments.

quote_list is the one of the mechanisms for creating list literal constants, also see make_list.  It is normally used for assigning initial values to lists, or for passing an anonymous macro to another macro.

Example

An example usage results in the list contains two strings followed by two integers.

list l;
l = quote_list("first", "second", 1, 2);

As an alternative the following syntax implies the use of quote_list by the GRIEF Macro compiler.

list l = {"first", "second", 1, 2};

Parameters

...One or more values to be made into list elements.

Returns

The quote_list() primitive returns the built list.

Portability

n/a

See Also

make_list, length_of_list, list_each, list_extract

search_list

int search_list( [int start],
string pattern,
 list expr,
 [int re],
 [int case])

Search list contents.

Description

The search_list() primitive searches the list expr against the expression pattern.  The treatment of the matched pattern may either be a regular-expression or constant string dependent on re and case folding based on case.

Note:

The search_list primitive is provided primary for Crisp compatibility.  Since re and case can reference the current global search states, inconsistent and/or unexpected results may result between usage; as such it is advised that the state-less re_search primitive is used by new macros.

Parameters

startOptional integer index, states the element offset at which search operation shall start.  If omitted, the search is started from the beginning of the list.
patternA string containing the pattern to be matched.
exprA list expression containing the list to be search for the specified pattern.
reOptional integer value.  If re is specified and is zero, then pattern is treated as a literal string not as a regular expression; behaviour being the same as index.  Otherwise the string shall be treated as a regular expression using the current global syntax, see re_syntax and search_back for additional information.
caseOptional integer value specifying whether case folding should occur.  If case is specified and is zero, then the search is done with case insensitive.  If omitted the current global setting is referenced.

Returns

The search_list() primitive returns the index of the matched element, otherwise -1 if no match.

Portability

n/a

See Also

list, re_search

shift

declare shift(list lst)

Shift the first list element.

Description

The shift() primitive removes (shifts) the first value of the list lst off and returns its, shortening the list by 1 and moving everything down.

If there are no elements in the list, the following is echoed onthe command promot and shift returns the null value.

shift: empty list.

Parameters

lstList expression.

Returns

The shift() primitive returns the first element on the list.

Examples

Iterator the list from the front, removing and then printing each element in the process;

list l = {"one", "two", "three", "four"};

while (length_of_list(l)) {
message("%s", shift(l));
}

the resulting output

one
two
three
four

Portability

A GriefEdit extension

See Also

pop, push, splice, car, cdr

sort_list

list sort_list(list lst,
  [string|int comparator = 0],
 [int type = 3])

Sort list.

Description

The sort_list() primitive sorts the list and returns the sorted array value.

By default elements are sorted alphabetically yet the sort can be modified using the user specified macro or using one of the predefined system sort macros.

Sort Method

GriefEdit 2.5.4 and earlier bindly utlilised the system supplied quicksort algorithm to implement sort.  The characteristics of the algorithm could not defined as such was normally unstable, plus may have gone quadratic.  (Although quicksort’s run time is O(NlogN) when averaged over all arrays of length N, the time can be O(N**2), quadratic behavior, for some inputs.

Following Perl and Java in 2.5.5 the default sort implementation was replaced with a stable mergesort algorithm whose worst-case behavior is O(NlogN).  In addition quicksort defends against quadratic behaviour by shuffling large arrays before sorting.

A stable sort means that for records that compare equal, the original input ordering is preserved.  Mergesort is stable, quicksort is not.  Stability will matter only if elements that compare equal can be distinguished in some other way.  That means that simple numerical and lexical sorts do not profit from stability, since equal elements are indistinguishable.  However, with a comparison such as

int
mysort(string a, string b)
{
return (substr(a, 0, 3) <=> substr(b, 0, 3));
}

stability might matter because elements that compare equal on the first 3 characters may be distinguished based on subsequent characters.  In Perl 5.8 and later, quicksort can be stabilized, but doing so will add overhead, so it should only be done if it matters.

The best algorithm depends on many things.  On average, mergesort does fewer comparisons than quicksort, so it may be better when complicated comparison routines are used.  Mergesort also takes advantage of pre-existing order, so it would be favored for using sort() to merge several sorted arrays.  On the other hand, quicksort is often faster for small arrays, and on arrays of a few distinct values, repeated many times.  You can force the choice of algorithm with the specification of the third argument.  The default algorithm is mergesort, which will be stable even if you do not explicitly demand it.  The stability of the default sort is a side-effect that could change in later versions.

int
mycmp(string a, string b)
{
return (a <=> b);
}

Note:

In the interests of efficiency the normal calling code for subroutines is bypassed, with the following effects: elements to be compared are passed into a and b, are passed by reference as such do not modify a and b.

Parameters

listList to be sorted.
comparatorOptional string comparison macro or integer direction.  A string value states the comparison macro to be executed.  Whereas an integer value states the direction, with zero selecting the built “sort_list::backward” comparator and a non-zero value selecting “sort_list::forward.  If omitted the comparator defaults to forward.
typeOptional integer stating the sort type, being
1quicksort.
2mergesort
3heapsort (default).

Returns

Sorted list.

Portability

Second argument allowing either a sort-order or user specified callback plus type selection are GriefEdit extensions.

See Also

sort_buffer

splice

int splice(list lst,  
int offset =  0,
  [int length],  
 [declare value]  )

Splice a list, removing and/or adding elements.

Description

The splice() primitive removes the elements designated by offset and length from an list, and replaces them with the elements of value, if any.

If offset is negative then it starts that far from the end of the list.

If length is negative, removes the elements from offset onward except for -length elements at the end of the list.

If length is omitted, removes everything from offset onward.  If both offset and length are omitted, removes everything.

If offset is past the end of the list, warning is issued and splices at the end of the list.

Parameters

lstList expression.
offsetNon-negative list offset from the front at which element are to be removed, when negative then it starts from the end.  If omitted removes from the head of the list.
lengthOptional number of elements to be remove.
valueOptional value to be inserted at the deletion point.

Examples

Equivalent

The splice primitive provides a general purpose list manipulation tool, which can be as a alternative to a number of specialise primitives.

The following macro primitives push, <+=>, pop, cdr, unshift use on the left are equivalent to right splice usage.

push(lst, x)
or lst += x splice(lst, length_of_list(a), 0, x)
pop(lst) splice(lst, -1)
cdr(lst) splice(lst, 0, 1)
unshift(lst, x) splice(lst, 0, 0, x)
lst[i] = y splice(lst, i, 1, y)
Flatten mode

Splice usage implies the non-flatting of a source list when appending into another, whereas list append operations shall flatten the source list at level 0, as such when used in the following context the result is;

list lst = make_list("a", "b");
lst += lst;
// result = "a", "b", "a", "b"

The alternative splice usage which shall place a list reference within the list.

splice(lst, length_of_list(lst), 0, lst);

Returns

nothing

Portability

A GriefEdit extension.

See Also

pop, push, shift, car, cdr

strlen

int strlen(string|list arg,
 [int step = 1])

String length.

Description

The strlen() primitive computes the length of arg.

For string arguments, computes the length of the string in character.

In the case arg is a list, computes the length of the longest string element contained within the list.  Non-string elements shall be omitted.  If specified and positive, iteration through the list shall only inspect each step element, starting with the first element within the list.

Parameters

argString or list.
stepOptional integer, stating the list iterator step value 1 or greater.

Returns

The strlen() primitive returns the number of characters contained within the string.

See Also

strnlen, length_of_list

strnlen

int strnlen(string|list arg,
int maxlen,
 [int step = 1])

String length limited to an explicit maximum.

Description

The strnlen() primitive computes the length of arg limited to maxlen.

For string arguments, computes the length of the string in character.

In the case arg is a list, computes the length of the longest string element contained within the list in characters.  Non-string elements shall be omitted.  If specified and positive, iteration through the list shall only inspect each step element, starting with the first element within the list.

Parameters

argString or list.
maxlenUpper limit to be applied to the length.
stepOptional integer, stating the iterator step value.

Returns

The strnlen() primitive returns either the same result as strlen() or maxlen, whichever is smaller.

Portability

A GriefEdit extension.

See Also

strlen

unshift

declare unshift(list lst,
declare value)

Shift the first list element.

Description

The unshift() primitive is reserved for future use.

The unshift() primitive performs the opposite action to that of a shift.  It prepends value to the front of the list lst returns the resulting number of elements within the list.

Parameters

lstList to be modified.
valueValue to be prepended.

Returns

The unshift() primitive returns the resulting number of list elements.

Portability

A GriefEdit extension.

See Also

pop, push, shift, splice, car, cdr

$Id: $

To send feedback on this topic email: grie.nosp@m.fedit@gmai.nosp@m.l.com

Copyright © Adam Young All Rights Reserved.

declare car(list lst)
Retrieve the first list element.
list cdr(list lst)
Retrieve all secondary list elements.
list command_list(  [int nomacros = FALSE],
[string pattern])
Retrieve list of built-in and active macros.
void delete_nth(list lst,
  [int offset = 0],
 [int length = 1])
Remove one or more elements from a list.
list file_glob(string files)
Return names of files that match patterns.
declare get_nth(int idx,
list expr)
Retrieve a list element.
int length_of_list(list lst)
Determine list element count.
list sym1, sym2 ...;
Declare a list symbol.
int list_each(list lst,
 declare &value,
 [int increment = 1])
Iterator though the list elements.
list list_extract(list lst,
 int start,
 [int end],
 [int increment])
Extract list elements.
int list_reset(list lst)
Reset the list iterator.
list make_list(...)
Build an evaluated list.
declare nth(list expr,
int idx,
 [int idx2 ...])
Extract the indexed list item.
declare pop(list expr)
Pop the last element.
declare push(list lst,
declare value ...)
Add an element onto a list.
declare put_nth(symbol,
...)
Modify a list element.
list quote_list(...)
Build an unevaluated list.
int search_list( [int start],
string pattern,
 list expr,
 [int re],
 [int case])
Search list contents.
declare shift(list lst)
Shift the first list element.
list sort_list(list lst,
  [string|int comparator = 0],
 [int type = 3])
Sort list.
int splice(list lst,  
int offset =  0,
  [int length],  
 [declare value]  )
Splice a list, removing and/or adding elements.
int strlen(string|list arg,
 [int step = 1])
String length.
int strnlen(string|list arg,
int maxlen,
 [int step = 1])
String length limited to an explicit maximum.
declare unshift(list lst,
declare value)
Shift the first list element.
int file_match(pattern,
file,
[flags])
File match utility.
list macro_list([string pattern = NULL])
Retrieve list of current macros.
string glob(string pattern)
Generate pathnames matching a pattern.
string file_canon(string filepath)
Canonicalize a path.
int file_pattern(string filespec)
Directory file pattern.
int find_file([string &filename],
[int &size],
 [int &mtime],
[int &ctime],
[int &mode])
Read next directory entry.
string expandpath(string path,
 [int env])
Expand the path.
Each object, reference, and function in Grief is associated with a type, which is defined at the point of declaration and cannot change.
int sym1, sym2 ...;
Declare an integer symbol.
string sym1, sym2 ...;
Declare a string symbol.
float sym1, sym2 ...;
Declare a float symbol.
double sym1, sym2 ...;
Declare a double float symbol.
array sym1, sym2 ...;
Declare a array symbol.
int re_search([int flags],
[string pattern],
 [declare object],
[int start],
[int lensym])
Search for a string.
int index(string str,
int ch|string s)
Search string for a leftmost sub-string or character.
int re_syntax([int re],
[int case],
[int capture])
Set the regular expression mode.
int search_back(string pattern,
 [int re],
 [int case],
  [int block],
 [int length])
Backwards buffer search.
int sort_buffer([int bufnum],
[string|int comparator = 0],
 [int start],
[int end],
[int type = 3])
Sort buffer content.