From 190696db9bc79ab28d4200324f4d971ae51e453b Mon Sep 17 00:00:00 2001 From: Pekka Laiho Date: Tue, 2 Jun 2020 18:03:05 +0700 Subject: [PATCH] add string functions --- bootstrap.php | 1 + src/Lib/Collections.php | 5 ++++- src/Lib/Strings.php | 46 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 src/Lib/Strings.php diff --git a/bootstrap.php b/bootstrap.php index b0b31b7..bd796fa 100644 --- a/bootstrap.php +++ b/bootstrap.php @@ -20,6 +20,7 @@ function ml_get_lisp(): array (new MadLisp\Lib\Collections())->register($env); (new MadLisp\Lib\Compare())->register($env); (new MadLisp\Lib\Math())->register($env); + (new MadLisp\Lib\Strings())->register($env); (new MadLisp\Lib\Types())->register($env); return [$lisp, $env]; diff --git a/src/Lib/Collections.php b/src/Lib/Collections.php index 3da2304..fdeda31 100644 --- a/src/Lib/Collections.php +++ b/src/Lib/Collections.php @@ -6,6 +6,7 @@ use MadLisp\CoreFunc; use MadLisp\Env; use MadLisp\Func; use MadLisp\Hash; +use MadLisp\MadLispException; use MadLisp\MList; use MadLisp\Seq; use MadLisp\Util; @@ -39,9 +40,11 @@ class Collections implements ILib function ($a) { if ($a instanceof Collection) { return $a->count(); - } else { + } elseif (is_string($a)) { return strlen($a); } + + throw new MadLispException('len required string or collection as argument'); } )); diff --git a/src/Lib/Strings.php b/src/Lib/Strings.php new file mode 100644 index 0000000..483cb40 --- /dev/null +++ b/src/Lib/Strings.php @@ -0,0 +1,46 @@ +set('trim', new CoreFunc('trim', 'Remove whitespace from beginning and end of string.', 1, 1, + fn (string $a) => trim($a) + )); + + $env->set('upcase', new CoreFunc('upcase', 'Return string in upper case.', 1, 1, + fn (string $a) => strtoupper($a) + )); + + $env->set('locase', new CoreFunc('locase', 'Return string in lower case.', 1, 1, + fn (string $a) => strtolower($a) + )); + + $env->set('substr', new CoreFunc('substr', 'Return substring starting from index as second argument and length as optional third argument.', 2, 3, + function (string $a, int $i, ?int $l = null) { + if ($l === null) { + return substr($a, $i); + } else { + return substr($a, $i, $l); + } + } + )); + + $env->set('split', new CoreFunc('split', 'Split the second argument by the first argument into a list.', 2, 2, + fn (string $a, string $b) => new MList(explode($a, $b)) + )); + + $env->set('join', new CoreFunc('join', 'Join the remaining arguments together by using the first argument as glue.', 1, -1, + fn (string $a, ...$b) => implode($a, $b) + )); + + $env->set('format', new CoreFunc('format', 'Format the remaining arguments as string specified by the first argument.', 1, -1, + fn (string $a, ...$b) => sprintf($a, ...$b) + )); + } +}