add 3 new functions for collections

This commit is contained in:
Pekka Laiho 2020-06-03 14:37:04 +07:00
parent 5e49f724fa
commit adc9664c69
2 changed files with 26 additions and 0 deletions

View File

@ -66,6 +66,8 @@ class Evaller
} }
return $value; return $value;
} elseif ($ast->get(0)->getName() == 'env') {
return $env;
} elseif ($ast->get(0)->getName() == 'fn') { } elseif ($ast->get(0)->getName() == 'fn') {
if ($ast->count() != 3) { if ($ast->count() != 3) {
throw new MadLispException("fn requires exactly 2 arguments"); throw new MadLispException("fn requires exactly 2 arguments");

View File

@ -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 // Hash map functions
$env->set('key?', new CoreFunc('key?', 'Return true if first argument (hash-map) contains the second argument as key.', 2, 2, $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, $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())) 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);
}
));
} }
} }