List Primitives | |
Macros | |
car | Retrieve the first list element. |
cdr | Retrieve all secondary list elements. |
command_list | Retrieve list of built-in and active macros. |
delete_nth | Remove one or more elements from a list. |
file_glob | Return names of files that match patterns. |
get_nth | Retrieve a list element. |
length_of_list | Determine list element count. |
list | Declare a list symbol. |
list_each | Iterator though the list elements. |
list_extract | Extract list elements. |
list_reset | Reset the list iterator. |
make_list | Build an evaluated list. |
nth | Extract the indexed list item. |
pop | Pop the last element. |
push | Add an element onto a list. |
put_nth | Modify a list element. |
quote_list | Build an unevaluated list. |
search_list | Search list contents. |
shift | Shift the first list element. |
sort_list | Sort list. |
splice | Splice a list, removing and/or adding elements. |
strlen | String length. |
strnlen | String length limited to an explicit maximum. |
unshift | Shift the first list element. |
declare car( list lst )
Retrieve the first list element.
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.
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.
TODO
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.
n/a
list cdr( list lst )
Retrieve all secondary list elements.
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.
TODO
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.
n/a
list command_list( [int nomacros = FALSE], [string pattern] )
Retrieve list of built-in and active macros.
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.
nomacros | Optional boolean value, if stated as true then only built-ins primitives are retrieved, filtering any run-time loaded macros. |
pattern | Optional 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). |
The command_list() primitive returns a list of strings each containing the name of a primitive or macro.
n/a
void delete_nth( list lst, [int offset = 0], [int length = 1] )
Remove one or more elements from a list.
The delete_nth() primitive deletes length elements from the specified list lst starting at the index offset.
lst | List reference which shall have elements removed. |
offset | Optional integer offset within list, if omitted defaults to the first element being offset 0. |
length | Optional 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. |
nothing
n/a
list file_glob( string files )
Return names of files that match patterns.
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. |
\x | Matches the character x. |
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.
declare get_nth( int idx, list expr )
Retrieve a list element.
The get_nth() primitive retrieves the element positioned at offset idx within the specified list expression expr.
This primitive is generally not utilised directly as the GRIEF language supports list offset operator of the form [idx].
The get_nth() primitive returns the value of the referenced element, otherwise NULL if the index is out of bounds.
n/a
int length_of_list( list lst )
Determine list element count.
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.
The length_of_list() primitive returns the top-level element count.
n/a
list sym1, sym2 ...;
Declare a list symbol.
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.
nothing
n/a
int list_each( list lst, declare & value, [int increment = 1] )
Iterator though the list elements.
The list_each() primitive iterates over a normal list value and sets the variable value to be each element of the list in turn.
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);
}
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.
lst | List expression. |
value | Variable populated with the element value. |
increment | Optional integer iterator loop increment, if omitted defaults to one element. |
The list_each() primitive returns the element index retrieved, otherwise -1 upon an end-of-list condition or error.
A GriefEdit extension.
make_list, quote_list, length_of_list, list_reset, list_extract
list list_extract( list lst, int start, [int end], [int increment] )
Extract list elements.
The list_extract() primitive iterates over the list values generating a new list of the referenced elements within the list.
lst | List expression. |
start | Optional 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. |
end | Optional 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. |
increment | Optional integer iterator loop increment, if omitted defaults to one element. |
The list_extract() primitive returns a list containing the referenced elements, otherwise a NULL list on error.
n/a
int list_reset( list lst )
Reset the list iterator.
The list_reset() primitive resets the list iteration cursor.
lst | List expression. |
The list_reset() primitive returns the selected element index.
A GriefEdit extension.
make_list, quote_list, length_of_list, list_each, list_extract
list make_list( ... )
Build an evaluated list.
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.
... | One or more values to be made into list elements. |
The make_list() primitive returns the built list.
n/a
declare nth( list expr, int idx, [int idx2 ...] )
Extract the indexed list item.
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.
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 [].
expr | List expression. |
idx | Integer index. |
... | None or more integer indexs of sub-elements. |
The nth() primitive returns the value of the specified element from the referenced list, otherwise NULL on error.
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.
declare pop( list expr )
Pop the last element.
The pop() primitive removes and returns the last value of the list, shortening the list by one element.
The pop() primitive returns the element removed, otherwise NULL on error.
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
A GriefEdit extension
declare put_nth( symbol, ... )
Modify a list element.
The put_nth() primitive modifies the element within the specified list.
This primitive is generally not utilised directly as the GRIEF language supports a list offset operator of the form [idx].
The put_nth() primitive returns the value of the referenced element, otherwise NULL if the index is out of bounds.
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.
list quote_list( ... )
Build an unevaluated list.
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.
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};
... | One or more values to be made into list elements. |
The quote_list() primitive returns the built list.
n/a
int search_list( [int start], string pattern, list expr, [int re], [int case] )
Search list contents.
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.
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.
start | Optional integer index, states the element offset at which search operation shall start. If omitted, the search is started from the beginning of the list. |
pattern | A string containing the pattern to be matched. |
expr | A list expression containing the list to be search for the specified pattern. |
re | Optional 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. |
case | Optional 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. |
The search_list() primitive returns the index of the matched element, otherwise -1 if no match.
n/a
declare shift( list lst )
Shift the first list element.
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.
lst | List expression. |
The shift() primitive returns the first element on the list.
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
A GriefEdit extension
list sort_list( list lst, [string|int comparator = 0], [int type = 3] )
Sort list.
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.
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);
}
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.
list | List to be sorted. |
comparator | Optional 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. |
type | Optional integer stating the sort type, being |
1 | quicksort. |
2 | mergesort |
3 | heapsort (default). |
Sorted list.
Second argument allowing either a sort-order or user specified callback plus type selection are GriefEdit extensions.
int splice( list lst, int offset = 0, [int length], [declare value] )
Splice a list, removing and/or adding elements.
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.
lst | List expression. |
offset | Non-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. |
length | Optional number of elements to be remove. |
value | Optional value to be inserted at the deletion point. |
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)
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);
nothing
A GriefEdit extension.
int strlen( string|list arg, [int step = 1] )
String length.
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.
arg | String or list. |
step | Optional integer, stating the list iterator step value 1 or greater. |
The strlen() primitive returns the number of characters contained within the string.
int strnlen( string|list arg, int maxlen, [int step = 1] )
String length limited to an explicit maximum.
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.
arg | String or list. |
maxlen | Upper limit to be applied to the length. |
step | Optional integer, stating the iterator step value. |
The strnlen() primitive returns either the same result as strlen() or maxlen, whichever is smaller.
A GriefEdit extension.
declare unshift( list lst, declare value )
Shift the first list element.
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.
lst | List to be modified. |
value | Value to be prepended. |
The unshift() primitive returns the resulting number of list elements.
A GriefEdit extension.
pop, push, shift, splice, car, cdr
$Id: $
To send feedback on this topic email: grie@gmai l.com fedit
Copyright © Adam Young All Rights Reserved.
Retrieve the first list element.
declare car( list lst )
Retrieve all secondary list elements.
list cdr( list lst )
Retrieve list of built-in and active macros.
list command_list( [int nomacros = FALSE], [string pattern] )
Remove one or more elements from a list.
void delete_nth( list lst, [int offset = 0], [int length = 1] )
Return names of files that match patterns.
list file_glob( string files )
Retrieve a list element.
declare get_nth( int idx, list expr )
Determine list element count.
int length_of_list( list lst )
Declare a list symbol.
list sym1, sym2 ...;
Iterator though the list elements.
int list_each( list lst, declare & value, [int increment = 1] )
Extract list elements.
list list_extract( list lst, int start, [int end], [int increment] )
Reset the list iterator.
int list_reset( list lst )
Build an evaluated list.
list make_list( ... )
Extract the indexed list item.
declare nth( list expr, int idx, [int idx2 ...] )
Pop the last element.
declare pop( list expr )
Add an element onto a list.
declare push( list lst, declare value ... )
Modify a list element.
declare put_nth( symbol, ... )
Build an unevaluated list.
list quote_list( ... )
Search list contents.
int search_list( [int start], string pattern, list expr, [int re], [int case] )
Shift the first list element.
declare shift( list lst )
Sort list.
list sort_list( list lst, [string|int comparator = 0], [int type = 3] )
Splice a list, removing and/or adding elements.
int splice( list lst, int offset = 0, [int length], [declare value] )
String length.
int strlen( string|list arg, [int step = 1] )
String length limited to an explicit maximum.
int strnlen( string|list arg, int maxlen, [int step = 1] )
Shift the first list element.
declare unshift( list lst, declare value )
File match utility.
int file_match( pattern, file, [flags] )
Retrieve list of current macros.
list macro_list( [string pattern = NULL] )
Generate pathnames matching a pattern.
string glob( string pattern )
Canonicalize a path.
string file_canon( string filepath )
Directory file pattern.
int file_pattern( string filespec )
Read next directory entry.
int find_file( [string &filename], [int &size], [int &mtime], [int &ctime], [int &mode] )
Expand the path.
string expandpath( string path, [int env] )
Declare an integer symbol.
int sym1, sym2 ...;
Declare a string symbol.
string sym1, sym2 ...;
Declare a float symbol.
float sym1, sym2 ...;
Declare a double float symbol.
double sym1, sym2 ...;
Declare a array symbol.
array sym1, sym2 ...;
Search for a string.
int re_search( [int flags], [string pattern], [declare object], [int start], [int lensym] )
Search string for a leftmost sub-string or character.
int index( string str, int ch|string s )
Set the regular expression mode.
int re_syntax( [int re], [int case], [int capture] )
Backwards buffer search.
int search_back( string pattern, [int re], [int case], [int block], [int length] )
Sort buffer content.
int sort_buffer( [int bufnum], [string|int comparator = 0], [int start], [int end], [int type = 3] )