From adc9664c699104aba2e8b16e3a06ca08c12296a5 Mon Sep 17 00:00:00 2001 From: Pekka Laiho Date: Wed, 3 Jun 2020 14:37:04 +0700 Subject: [PATCH] add 3 new functions for collections --- src/Evaller.php | 2 ++ src/Lib/Collections.php | 24 ++++++++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/src/Evaller.php b/src/Evaller.php index fd71c80..49e7b7e 100644 --- a/src/Evaller.php +++ b/src/Evaller.php @@ -66,6 +66,8 @@ class Evaller } return $value; + } elseif ($ast->get(0)->getName() == 'env') { + return $env; } elseif ($ast->get(0)->getName() == 'fn') { if ($ast->count() != 3) { throw new MadLispException("fn requires exactly 2 arguments"); diff --git a/src/Lib/Collections.php b/src/Lib/Collections.php index 1f1d105..0f956b8 100644 --- a/src/Lib/Collections.php +++ b/src/Lib/Collections.php @@ -104,6 +104,10 @@ class Collections implements ILib } )); + $env->set('reverse', new CoreFunc('reverse', 'Create new sequence with reversed order.', 1, 1, + fn (Seq $a) => $a::new(array_reverse($a->getData())) + )); + // Hash map functions $env->set('key?', new CoreFunc('key?', 'Return true if first argument (hash-map) contains the second argument as key.', 2, 2, @@ -133,5 +137,25 @@ class Collections implements ILib $env->set('values', new CoreFunc('values', 'Return the values of a hash-map as a list.', 1, 1, fn (Hash $a) => new MList(array_values($a->getData())) )); + + $env->set('zip', new CoreFunc('zip', 'Create new hash-map using first argument as keys and second argument as values.', 2, 2, + function (Seq $keys, Seq $vals) { + if ($keys->count() != $vals->count()) { + throw new MadLispException('zip requires equal number of keys and values'); + } + + return new Hash(array_combine($keys->getData(), $vals->getData())); + } + )); + + // Sorting + + $env->set('sort', new CoreFunc('sort', 'Sort the sequence in ascending order.', 1, 1, + function (Seq $a) { + $data = $a->getData(); + sort($data); + return $a::new($data); + } + )); } }