Skip to content

Commit 8172797

Browse files
committed
Add an S-OR macro.
See #132
1 parent 69ef8b4 commit 8172797

3 files changed

Lines changed: 47 additions & 0 deletions

File tree

README.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@ The only dependency is `cl-ppcre`.
9090
- [Macros](#macros)
9191
- [string-case](#string-case)
9292
- [match (experimental) · new in Feb, 2024](#match-experimental--new-in-feb-2024)
93+
- [s-or](#s-or)
9394
- [Changelog](#changelog)
9495
- [Dev and test](#dev-and-test)
9596
- [Main test suite](#main-test-suite)
@@ -961,6 +962,21 @@ Match with regexs:
961962
;; => " hello "
962963
```
963964

965+
### s-or
966+
967+
Similar to OR, but finds the first argument that is not `(STR:EMPTYP)`.
968+
969+
```lisp
970+
(str:s-or "" "foo")
971+
;; => "foo"
972+
973+
(str:s-or nil "foo")
974+
;; => "foo"
975+
976+
(str:s-or "foo" (error "will not be evaluated"))
977+
;; => "foo"
978+
```
979+
964980
## Changelog
965981

966982
* September, 2025:

str.lisp

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@
3838
#:suffixp
3939
#:add-prefix
4040
#:add-suffix
41+
#:s-or
4142

4243
#:ensure
4344
#:ensure-prefix
@@ -1306,6 +1307,19 @@ unless MERGE-NUMBERS is non-nil.
13061307
""
13071308
(replace-non-word s))))
13081309

1310+
(defmacro s-or (&rest args)
1311+
"Similar to CL:OR, but returns the first non-empty string. If all the
1312+
strings are empty or NIL, then we return NIL.
1313+
1314+
Like OR, expressions are evaluated from left to right, until the first
1315+
expression returns a non-empty string."
1316+
(let ((var (gensym)))
1317+
`(or
1318+
,@ (loop for arg in args
1319+
collect `(let ((var ,arg))
1320+
(unless (str:emptyp var)
1321+
var))))))
1322+
13091323
;; "deprecated" function alias
13101324
(setf (fdefinition 'prune) #'shorten
13111325
(fdefinition 'common-prefix) #'prefix

test/test-str.lisp

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -793,3 +793,20 @@ def"))
793793
s)
794794
(t "nothing")))
795795
"match with the regex"))
796+
797+
(test s-or
798+
(is (equal
799+
"foo"
800+
(str:s-or nil "foo" "bar")))
801+
(is (equal
802+
"foo"
803+
(str:s-or "" "foo" "bar")))
804+
(is (equal
805+
nil
806+
(str:s-or)))
807+
(is (equal
808+
nil
809+
(str:s-or "" "")))
810+
(is (equal
811+
"foo"
812+
(str:s-or "foo" (error "will not be evaluated")))))

0 commit comments

Comments
 (0)