Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through a string in lisp for alpha chars OR space

I'm looking for how to loop through a string in LISP to check for alpha char or spaces. A sentence like "Coffee is Friend" is something that i want to check as Valid. But when i do (every #'alpha-char-p "coffee is best"') it fails on the spaces because the space is not technically alpha-char. Suggestions?

Thanks!

like image 419
Mitchell McLaughlin Avatar asked Apr 17 '16 19:04

Mitchell McLaughlin


3 Answers

Simply test for alpha-char or space:

 (every 
   (lambda (c) (or (alpha-char-p c) (char= c #\Space))) 
   "coffee is best")

every takes as first parameter a function that must return non-nil on every element of the sequence second parameter.

like image 100
Renzo Avatar answered Nov 01 '22 20:11

Renzo


Using LOOP:

CL-USER > (loop for c across "tea is best"
                always (or (alpha-char-p c)
                           (char= c #\space)))
T
like image 43
Rainer Joswig Avatar answered Nov 01 '22 18:11

Rainer Joswig


Depending on the complexity of the task, you might as well use regular expressions. If you load CL-PPCRE, you can write:

(ppcre:scan "^[ a-zA-Z]*$"  "Coffee is Friend")

The regular expression that is accepted by the library is a Perl-like string, or a parse-tree. For example, calling (ppcre:parse-string "^[ a-zA-Z]*$") gives:

(:SEQUENCE 
 :START-ANCHOR
 (:GREEDY-REPETITION 0
                     NIL
                     (:CHAR-CLASS #\
                                  (:RANGE #\a #\z)
                                  (:RANGE #\A #\Z)))
 :END-ANCHOR)

The above form has its uses when you have to combine regular expressions, because it is much easier than concatenating and escaping strings.

like image 4
coredump Avatar answered Nov 01 '22 20:11

coredump