mirror of
https://github.com/zaphar/ucg.git
synced 2025-07-21 18:10:42 -04:00
FEATURE: Add head and tail functions to our list library.
This commit is contained in:
parent
00cc246903
commit
7ae6955066
@ -36,7 +36,7 @@ l.str_join{
|
||||
|
||||
## len
|
||||
|
||||
The len module returns the length of a list. It has a single required parameter.
|
||||
The len function returns the length of a list. It has a single required parameter.
|
||||
|
||||
* `list` The list to reverse.
|
||||
|
||||
@ -45,6 +45,24 @@ let l = import "std/lists.ucg";
|
||||
l.len{list=[0, 1, 2, 3]} == 4;
|
||||
```
|
||||
|
||||
## head and tail
|
||||
|
||||
The `tail` function returns the tail of a list minus it's head.
|
||||
|
||||
```
|
||||
let l = import "std/lists.ucg";
|
||||
let tail = l.tail([0,1,2,3]);
|
||||
tail == [1,2,3];
|
||||
```
|
||||
|
||||
The `head` function returns the head of the list as a list of one item.
|
||||
|
||||
```
|
||||
let l = import "std/lists.ucg";
|
||||
let hd = l.head([0,1,2,3]);
|
||||
tail == [0];
|
||||
```
|
||||
|
||||
## enumerate
|
||||
|
||||
The enumerate module enumerates the elements of a list. It has three parameters.
|
||||
|
@ -29,6 +29,24 @@ let len = func(list) => reduce(func(acc, item) => acc + 1, 0, list);
|
||||
// Reverses the provided list.
|
||||
let reverse = func(list) => reduce(func (acc, item) => [item] + acc, [], list);
|
||||
|
||||
// head returns the first item in a list as a list of one item.
|
||||
// This function is safe for empty list inputs but is not safe
|
||||
// for NULL inputs.
|
||||
let head = func(list) => select len(list) > 0, [], {
|
||||
true = [list.0],
|
||||
};
|
||||
|
||||
// tail returns the tail of a list without the head.
|
||||
// This function is safe for empty lists but is not safe
|
||||
// for NULL inputs.
|
||||
let tail = func(list) => reduce(
|
||||
func (acc, item) => select acc.count > 0, acc{count=1, tail=[]}, {
|
||||
true = acc{count = acc.count + 1, tail = acc.tail + [item]},
|
||||
},
|
||||
{count=0},
|
||||
list,
|
||||
).tail;
|
||||
|
||||
// Enumerates the provided list with optional start and step parameters for the
|
||||
// enumeration. Prodices a list of pairs with the numeration and the list item.
|
||||
//
|
||||
|
@ -43,3 +43,13 @@ assert asserts.equal{
|
||||
left=list.zip{list1=[0, 1], list2=[3, 4]},
|
||||
right=[[0, 3], [1, 4]],
|
||||
};
|
||||
|
||||
assert asserts.equal{
|
||||
left=list.tail([0,1,2,3,4]),
|
||||
right=[1,2,3,4],
|
||||
};
|
||||
|
||||
assert asserts.equal{
|
||||
left=list.head([0,1,2,3,4]),
|
||||
right=[0],
|
||||
};
|
Loading…
x
Reference in New Issue
Block a user