Difference between eq? and = in Scheme?

不羁岁月 提交于 2019-12-10 13:40:35

问题


    > (eq? 1 1)
    #t
    > (eq? 1.1 1.1)
    #f
    > (= 1.1 1.1)
    #t

This is the interaction window in DrScheme. Could somebody please explain the difference between = and eq? in Scheme?


回答1:


= compares numbers. eq? tests if the parameters represent the same data object in memory. eqv? should work in the second case as it tests same as eq? but tests primitives specially. More on equlivence predicates in scheme here.




回答2:


I would guess that since

eq? evaluates to #f unless its parameters represent the same data object in memory;

and

Scheme stores inexact numbers (1.1) differently from exact numbers (1)

The two 1.1 arguments do not reside in the same place in memory and return #f for eq?

Wikipedia Reference




回答3:


eq? on numbers is unpredictable. It's up to the implementation or not whether numeric literals are interred so that the same numbers are in the same location in memory. The Racket language, for example, has recently chosen to intern such literals during reading. http://www.mail-archive.com/dev@racket-lang.org/msg04893.html

You won't know for sure whether or not your language implementation's runtime will represent each number uniquely. This can affect values that are boxed, like floats and bignums. That's why = exists as a predicate for numbers: it checks for the equal-ness of the content, rather than shallow pointer equality.

This isn't exclusive to languages like Scheme: equality vs equalness occurs in Python (is vs. ==) for example.




回答4:


first difference: eq? works with any pair of values, while = works with any number of numbers.

there are several other equivalence predicates. Most of them only accept exactly two parameters. = is defined in the 'numbers' chapter



来源:https://stackoverflow.com/questions/941817/difference-between-eq-and-in-scheme

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!