pushkin
pushkin

Reputation: 10217

Scheme - Check if element of list is a single letter

I have a list `(+ 1 2 3 a b c)

I want to check if an element is a letter.

(symbol? (list-ref mylist idx)) will return #t for both a and +, which I don't want.

Perhaps I could compare the element to [a-zA-z], or check if it's a symbol that's not [+-*/], but that seems tedious.

How is this done?

Update:

Actually, I could just write my own function.

(define is-letter
  (lambda (c)
    (if (and (not (number? c))
         (not (eq? c `+)) (not (eq? c `-)) (not (eq? c `*)) (not (eq? c '/)))
      #t
      #f
    )
  )
)

Upvotes: 0

Views: 2726

Answers (1)

Óscar López
Óscar López

Reputation: 236034

Given that you intend to use a quoted list, here's a possible solution that works by converting symbols to strings and then checking for the condition:

(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)))))) 

For example:

(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

Upvotes: 3

Related Questions