(zip [l1] [l2])

This commit is contained in:
2020-12-05 19:06:15 -07:00
parent 1805b396bf
commit 2fd60370e8
4 changed files with 47 additions and 7 deletions

View File

@@ -50,7 +50,7 @@ class Kiss {
// Helpful aliases
k.defAlias("print", Symbol("Prelude.print"));
k.defAlias("groups", Symbol("Prelude.groups"));
k.defAlias("zip", Symbol("Prelude.zip"));
k.defAlias("map", Symbol("Lambda.map"));
k.defAlias("filter", Symbol("Lambda.filter")); // TODO use truthy as the default filter function
k.defAlias("has", Symbol("Lambda.has"));

View File

@@ -158,6 +158,34 @@ class Prelude {
return fullGroups;
}
public static function zip<A, B>(a:Array<A>, b:Array<B>, extraHandling = Drop):Array<Array<Dynamic>> {
var max = Math.floor(if (a.length != b.length) {
switch (extraHandling) {
case Throw:
throw 'zip was given lists of mis-matched size: $a, $b';
case Keep:
Math.max(a.length, b.length);
case Drop:
Math.min(a.length, b.length);
}
} else {
a.length;
});
return [
for (idx in 0...max) [
if (idx < a.length)
a[idx]
else
null,
if (idx < b.length)
b[idx]
else
null
]
];
}
public static dynamic function truthy(v:Any) {
return switch (Type.typeof(v)) {
case TNull: false;

View File

@@ -136,8 +136,11 @@ class BasicTestCase extends Test {
}
function testGroups() {
Assert.equals([[1, 2], [3, 4]].toString(), BasicTestCase.myGroups1().toString());
Assert.equals([[1, 2, 3], [4]].toString(), BasicTestCase.myGroups2().toString());
_testGroups();
}
function testZip() {
_testZip();
}
function testLet() {

View File

@@ -114,11 +114,20 @@
(defun myTypeCheck []
(the Int 5))
(defun myGroups1 []
(groups [1 2 3 4] 2))
(defun _testGroups []
(Assert.equals (.toString [[1 2] [3 4]]) (.toString (groups [1 2 3 4] 2)))
(Assert.equals (.toString [[1 2 3] [4]]) (.toString (groups [1 2 3 4] 3 Keep)))
(try (begin (groups [1 2 3 4] 3 Throw) (Assert.fail))
(catch [error] (Assert.pass))))
(defun myGroups2 []
(groups [1 2 3 4] 3 Keep))
(defun _testZip []
(Assert.equals (.toString [[1 2] [3 4]]) (.toString (zip [1 3] [2 4] Throw)))
(Assert.equals (.toString [[1 2] [3 null]]) (.toString (zip [1 3] [2] Keep)))
(Assert.equals (.toString [[1 2] [null 4]]) (.toString (zip [1 null] [2 4] Keep)))
(try (begin (zip [1 3] [2] Throw) (Assert.fail))
(catch [error] (Assert.pass)))
(try (begin (zip [1] [2 4] Throw) (Assert.fail))
(catch [error] (Assert.pass))))
(defun _testLet []
(let [a 5