Check if an argument is a list or an atom
Asked Answered
S

2

17

How do I check if something is an atom? I'm looking for something like number? or list?.

Selfaggrandizement answered 23/3, 2011 at 11:43 Comment(1)
In case it's not clear from the answers below: the term "atom" is used differently by different authors and in different systems. If you're reading a particular text, you probably want to use the definition of 'atom' given in the text. This is probably the principal reason that no 'atom?' primitive exists in the system you're using.Poinsettia
L
22

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

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

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

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

And of course you can add much more here -- since it's marked as a racket question, you might want to add hash tables, structs, etc etc. So it can just as well be easier to specify the kinds of values that you do consider as 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?))
Lal answered 23/3, 2011 at 20:13 Comment(0)
S
5

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

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

This will return true if x is not a pair (or a list). It will return true for numbers, strings, characters, and symbols, while symbol? will only return true for symbols, naturally. This might or might not be what you want. Compare Yasir Arsanukaev's 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 proper lists like (1 2 3), pairs like (a . b), while list? will return false for dotted pairs and dotted-tail lists.

Sensuality answered 23/3, 2011 at 12:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.