[ACCEPTED]-Check if an argument is a list or an atom-racket

Accepted answer
Score: 22

Usually, you'll want to exclude the empty 8 list too:

(define (atom? x) (not (or (pair? x) (null? x))))

or, if you want to be more pedantic, then 7 forbid vectors too:

(define (atom? x) (not (or (pair? x) (null? x) (vector? x))))

And of course you can 6 add much more here -- since it's marked 5 as a racket question, you might want to 4 add hash tables, structs, etc etc. So it 3 can just as well be easier to specify the 2 kinds of values that you do consider as 1 atoms:

(define (atom? x)
   (ormap (lambda (p) (p x)) (list number? symbol? boolean? string?)))

or using the racket contract system:

(define atom? (or/c number? symbol? boolean? string?))
Score: 5

When various Schemes don't include it, I've 10 often seen atom? defined this way:

(define (atom? x) (not (pair? x)))

This will return 9 true if x is not a pair (or a list). It will 8 return true for numbers, strings, characters, and 7 symbols, while symbol? will only return true for 6 symbols, naturally. This might or might 5 not be what you want. Compare Yasir Arsanukaev's 4 example:

1 ]=> (map atom? (list 42 'a-symbol (list 12 13) 'foo "yiye!"))

;Value 13: (#t #t #f #t #t)

It uses pair? because this checks for 3 proper lists like (1 2 3), pairs like (a . b), while list? will 2 return false for dotted pairs and dotted-tail 1 lists.

More Related questions