summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorOwen Jacobson <owen@grimoire.ca>2017-12-10 23:48:55 -0500
committerOwen Jacobson <owen@grimoire.ca>2017-12-10 23:48:55 -0500
commit887f84d00cd7e59efe4329cb59c3e5f7a460c221 (patch)
treec402bb30ea700005415bc2a8316b456a952a07fe
parent214ce2eff6836018e4d1b5cc89360be9db763514 (diff)
Some basic iteration primitives.
-rw-r--r--actinide/stdlib.py18
-rw-r--r--docs/builtin.rst65
2 files changed, 83 insertions, 0 deletions
diff --git a/actinide/stdlib.py b/actinide/stdlib.py
index 5e46f3a..546e3f5 100644
--- a/actinide/stdlib.py
+++ b/actinide/stdlib.py
@@ -95,3 +95,21 @@ def let(symbols, bindings, *body):
@An.fn
def concat(*strings):
return ''.join(strings)
+
+def single_valued(fn):
+ def wrapper(*args, **kwargs):
+ result, = fn(*args, **kwargs)
+ return result
+ return wrapper
+
+@An.fn
+def filter(pred, vals):
+ return list(*b.filter(single_valued(pred), flatten(vals)))
+
+@An.fn
+def map(fn, vals):
+ return list(*b.map(single_valued(fn), flatten(vals)))
+
+@An.fn
+def reduce(fn, vals):
+ return f.reduce(single_valued(fn), flatten(vals))
diff --git a/docs/builtin.rst b/docs/builtin.rst
index e6da907..630a822 100644
--- a/docs/builtin.rst
+++ b/docs/builtin.rst
@@ -526,6 +526,27 @@ Returns:
Expands a form, applying macro expansion and converting shorthand forms into
their longhand equivalents.
+filter
+~~~~~~
+
+Syntax:
+
+.. code-block:: scheme
+
+ (filter fn list)
+
+Arguments:
+
+* ``fn``: a boolean function taking one argument.
+* ``list``: any list.
+
+Returns:
+
+* A list, which contains a subset of the entries from ``list``.
+
+The resulting list contains only the values ``v`` from ``list`` where ``(fn
+v)`` is true.
+
.. _head:
head
@@ -722,6 +743,27 @@ Returns:
* A vector containing the same elements as ``list``, in the same order.
+map
+~~~
+
+Syntax:
+
+.. code-block:: map
+
+ (map fn list)
+
+Arguments:
+
+* ``fn``: any procedure accepting one value and returning one value.
+* ``list``: any list.
+
+Returns:
+
+* A list of results.
+
+Applies ``fn`` to each element of ``list``, returning a list of the resulting
+values in the same order.
+
.. _nil:
nil
@@ -901,6 +943,29 @@ This consumes the characters returned - they will not be returned in future
calls to ``peek-port`` or ``read-port`` on the same port. If the port is fully
consumed, this will return the empty string.
+reduce
+~~~~~~
+
+Syntax:
+
+.. code-block:: scheme
+
+ (reduce fn list)
+
+Arguments:
+
+* ``fn``: any procedure taking two arguments and returning one value.
+* ``list``: any non-empty list.
+
+Returns:
+
+* The result of reducing the list through ``fn``, in left-to-right order.
+
+This passes the first two elements of ``list`` to ``fn``, then passes the
+result and the third element of ``list`` to ``fn``, and so on, until the list
+is exhausted, and returns the result. As a special case, if ``list`` has a
+single element, this returns it as-is.
+
.. _string:
string