方案 - 检查列表的元素是否是单个字母
Scheme - Check if element of list is a single letter
我有一个列表`(+ 1 2 3 a b c)
我想检查一个元素是否是一个字母。
(symbol? (list-ref mylist idx))
将 return #t
用于 a
和 +
,这是我不想要的。
也许我可以将该元素与 [a-zA-z]
进行比较,或者检查它是否是一个不是 [+-*/]
的符号,但这看起来很乏味。
这是怎么做到的?
更新:
实际上,我可以自己编写函数。
(define is-letter
(lambda (c)
(if (and (not (number? c))
(not (eq? c `+)) (not (eq? c `-)) (not (eq? c `*)) (not (eq? c '/)))
#t
#f
)
)
)
鉴于您打算使用引号列表,这里有一个可能的解决方案,它通过将符号转换为字符串然后检查条件来工作:
(define (is-single-letter? x)
(if (number? x)
#f
(let ((s (symbol->string x)))
(and (= (string-length s) 1)
(char-alphabetic? (string-ref s 0))))))
例如:
(define mylist '(+ 1 2 3 a b c xxx))
(is-single-letter? (list-ref mylist 0)) ; + is an operator
=> #f
(is-single-letter? (list-ref mylist 2)) ; 2 is a number
=> #f
(is-single-letter? (list-ref mylist 4)) ; a is a single letter
=> #t
(is-single-letter? (list-ref mylist 7)) ; xxx is not a single letter
=> #f
我有一个列表`(+ 1 2 3 a b c)
我想检查一个元素是否是一个字母。
(symbol? (list-ref mylist idx))
将 return #t
用于 a
和 +
,这是我不想要的。
也许我可以将该元素与 [a-zA-z]
进行比较,或者检查它是否是一个不是 [+-*/]
的符号,但这看起来很乏味。
这是怎么做到的?
更新:
实际上,我可以自己编写函数。
(define is-letter
(lambda (c)
(if (and (not (number? c))
(not (eq? c `+)) (not (eq? c `-)) (not (eq? c `*)) (not (eq? c '/)))
#t
#f
)
)
)
鉴于您打算使用引号列表,这里有一个可能的解决方案,它通过将符号转换为字符串然后检查条件来工作:
(define (is-single-letter? x)
(if (number? x)
#f
(let ((s (symbol->string x)))
(and (= (string-length s) 1)
(char-alphabetic? (string-ref s 0))))))
例如:
(define mylist '(+ 1 2 3 a b c xxx))
(is-single-letter? (list-ref mylist 0)) ; + is an operator
=> #f
(is-single-letter? (list-ref mylist 2)) ; 2 is a number
=> #f
(is-single-letter? (list-ref mylist 4)) ; a is a single letter
=> #t
(is-single-letter? (list-ref mylist 7)) ; xxx is not a single letter
=> #f