Scheme - eq? compare between 2 strings?
I have a problem in my program.
I have a condition that compare between 2 string:开发者_如何学Go
(if (eq? (exp1) (exp2)))
When exp1 give me a string, and exp2 give me a string. To be sure, when I change the "eq?" to "=", it give me the next problem:
=: expects type <number> as 2nd argument, given: ie; other arguments were: ie.
When I'm running the program, the function doesnt enter to the first expression in the "if" function, and enter to the second one (meaning the condition is false).
What can I do?
Thank you.
According to the Equivalence predicates section of R6RS, you should be using equal?
, not eq?
, which instead tests whether its two arguments are exactly the same object (not two objects with the same value).
(eq? "a" "a") ; unspecified
(equal? "abc" "abc") ; #t
As knivil notes in a comment, the Strings section also mentions string=?
, specifically for string comparisons, which probably avoids doing a type check.
I wrote a little helper function for this problem.
; test if eq?
(define ==
(lambda (x y)
(if (and (string? x) (string? y))
(string=? x y)
(if (or (string? x) (string? y))
(= 1 0) ;return false
(equal? x y)))))
(define a "aString")
(define l '("aString" "aOtherString"))
(== (car l) a) ; true
(== 1 1) ; true
(== 1 0) ; false
(== "a" 1) ; false diff. type
(== "a" "b") ; false
(== "a" "a") ; true
(== '("a" "b") '("a" "b"))
精彩评论