Others already mentioned 'equal?' as the correct predicate for testing
structural content equality. It works not only for strings but also
arbitrarily nested structures, for instance:
(define a (list 'a 9871239876234 "foo" (vector #\a #\b #\c)))
(define b '(a 9871239876234 (string #\f #\o #\o) #(#\a #\b #\c)))
(equal? a b) ;=> #t
(define c "foo")
(define d 1234)
(equal? c d) ;=> #f (obviously)
But if you know that two variables both reference a string object,
there's a more appropriate predicate which explicitly tests for string
equality: 'string=?'
(define a "foo")
(define b (string #\f #\o #\o))
(string=? a b) ;=> #t
(define c "foo")
(define d 1234)
(string=? c d) ;=> ERROR: wrong type argument 1234 passed to string=?
Using 'string=?' instead of 'equal?' has a few small advantages in this
case:
- It makes it obvious to the reader of the code that two variables are
both supposed to reference a string.
- If due to some strange mistake one or both of the variables end up
referencing an object that is not a string, the 'string=?' call will
immediately raise an exception, which is probably better than it just
returning #f and letting the code continue to run, because the code will
probably crash at a later point anyway due to the object with the wrong
type. (It's best for code to crash as soon as possible when an error
like that happens, so you can find the root cause easily.)
- Lastly, 'string=?' probably has a tiny performance advantage, though
that's probably not important here. (If you experience performance
issues with your code, you should benchmark it to see where the actual
issue is. I'm just mentioning this for completeness' sake.)
Of course if your variables may contain different types of values like
lists and vectors and not just strings, you should indeed use 'equal?'.
- Taylan