additional list functions (range, map, filter, reduce, flatten) (#74)
also make the VM cope with reentrancy
This commit is contained in:
parent
2b924c3efb
commit
65645f410f
4 changed files with 341 additions and 47 deletions
|
@ -624,6 +624,93 @@ The first element is located at index 0.
|
|||
|
||||
Indexing out of bounds is an error.
|
||||
|
||||
```haku
|
||||
range
|
||||
min : number
|
||||
max : number
|
||||
-> list number
|
||||
```
|
||||
|
||||
Generates a list of integers from `min` to `max` (inclusive).
|
||||
|
||||
- When `max > min`, the integers go in an increasing order.
|
||||
- When `min > max`, the integers go in a decreasing order.
|
||||
|
||||
Note that this function consumes fuel proportional to the amount of elements in the generated list.
|
||||
|
||||
```haku
|
||||
map
|
||||
l : list t
|
||||
f : \t -> u
|
||||
-> list u
|
||||
```
|
||||
|
||||
Produces a new list containing all the elements of `l`, run through the function `f` one by one.
|
||||
|
||||
```haku
|
||||
filter
|
||||
l : list t
|
||||
f : \t -> boolean
|
||||
-> list t
|
||||
```
|
||||
|
||||
Produces a new list with only those elements of `l` for which `f` returns `True`.
|
||||
|
||||
```haku
|
||||
reduce
|
||||
l : list t
|
||||
init : a
|
||||
f : \a, t -> a
|
||||
-> a
|
||||
```
|
||||
|
||||
Reduces the list to a single element, by repeatedly applying a reducing operation `f` on its elements.
|
||||
|
||||
This reducing operation receives the current value of an _accumulator_ variable (first argument), and the current element being iterated (second argument).
|
||||
Its task is to return the _next_ value of the accumulator variable, which then gets passed into the next element, and so on and so forth.
|
||||
|
||||
```haku
|
||||
flatten
|
||||
l : list _
|
||||
-> list _
|
||||
```
|
||||
|
||||
Returns a new list with a single level of nesting flattened.
|
||||
|
||||
---
|
||||
|
||||
Some of these operations may be a bit confusing, so here are some examples.
|
||||
|
||||
```haku
|
||||
-- To add two to all elements in a list:
|
||||
list = range 1 4 -- [1, 2, 3, 4]
|
||||
twoAdded = map list \x ->
|
||||
x + 2
|
||||
```
|
||||
|
||||
```haku
|
||||
-- To filter out only even numbers in a list:
|
||||
list = range 1 10
|
||||
isEven = \x -> mod x 2 == 0
|
||||
onlyEven = filter list isEven
|
||||
```
|
||||
|
||||
```haku
|
||||
-- To sum all the numbers in a list:
|
||||
list = [1, 3, 10, 2, 30, 4, 1]
|
||||
sum = reduce list 0 \acc, value -> acc + value
|
||||
```
|
||||
|
||||
```haku
|
||||
-- To flatten a singly-nested list:
|
||||
list = [[1, 2], [3, 4], [5, 6]]
|
||||
flatList = flatten list -- [1, 2, 3, 4, 5, 6]
|
||||
|
||||
-- Note that this only applies to a single level of nesting:
|
||||
deepList = [[[1, 2, 3, 4]]]
|
||||
lessDeepList = flatten deepList -- [[1, 2, 3, 4]]
|
||||
```
|
||||
|
||||
|
||||
## Shapes
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue