add funcs for string comparison, support strings in reverse

This commit is contained in:
Pekka Laiho 2020-12-21 07:51:31 +07:00
parent 3941f9c99e
commit b4d8715525
2 changed files with 30 additions and 1 deletions

View File

@ -248,7 +248,15 @@ 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()))
function ($a) {
if ($a instanceof Seq) {
return $a::new(array_reverse($a->getData()));
} elseif (is_string($a)) {
return strrev($a);
}
throw new MadLispException('argument to reverse is not sequence or string');
}
));
// Hash map functions

View File

@ -15,6 +15,9 @@ class Strings implements ILib
{
public function register(Env $env): void
{
// Note that some functions in the Collections library
// work for strings as well: empty?, len, reverse
$env->set('EOL', \PHP_EOL);
$env->set('trim', new CoreFunc('trim', 'Remove whitespace from beginning and end of string. Give characters to remove in optional second argument.', 1, 2,
@ -109,6 +112,24 @@ class Strings implements ILib
fn (string $str, string $end) => substr($str, strlen($str) - strlen($end)) === $end
));
// Comparison functions
$env->set('strcmp', new CoreFunc('strcmp', 'Compare two strings.', 2, 2,
fn (string $a, string $b) => strcmp($a, $b)
));
$env->set('strcasecmp', new CoreFunc('strcasecmp', 'Compare two strings case-insensitively.', 2, 2,
fn (string $a, string $b) => strcasecmp($a, $b)
));
$env->set('strnatcmp', new CoreFunc('strnatcmp', 'Compare two strings using natural ordering.', 2, 2,
fn (string $a, string $b) => strnatcmp($a, $b)
));
$env->set('strnatcasecmp', new CoreFunc('strnatcasecmp', 'Compare two strings case-insensitively using natural ordering.', 2, 2,
fn (string $a, string $b) => strnatcasecmp($a, $b)
));
// If the mbstring extension is loaded,
// define multibyte versions of some functions.