guile-user
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Surprising behavior of eq?


From: Taylan Kammer
Subject: Re: Surprising behavior of eq?
Date: Sun, 20 Sep 2020 19:26:35 +0200
User-agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:68.0) Gecko/20100101 Thunderbird/68.12.0

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



reply via email to

[Prev in Thread] Current Thread [Next in Thread]