Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer equality in Haskell?

Is there any notion of pointer quality in Haskell? == requires things to be deriving Eq, and I have something which contains a (Value -> IO Value), and neither -> nor IO derive Eq.

EDIT: I'm creating an interpreter for another language which does have pointer equality, so I'm trying to model this behavior while still being able to use Haskell functions to model closures.

EDIT: Example: I want a function special that would do this:

> let x a = a * 2
> let y = x
> special x y
True
> let z a = a * 2
> special x z
False
like image 891
Claudiu Avatar asked Nov 11 '09 19:11

Claudiu


4 Answers

EDIT: Given your example, you could model this with the IO monad. Just assign your functions to IORefs and compare them.

Prelude Data.IORef> z <- newIORef (\x -> x)
Prelude Data.IORef> y <- newIORef (\x -> x)
Prelude Data.IORef> z == z
True
Prelude Data.IORef> z == y
False
like image 152
NicholasM Avatar answered Nov 08 '22 12:11

NicholasM


Pointer equality would break referential transparency, so NO.

Perhaps surprisingly, it is actually possible to compute extensional equality of total functions on compact spaces, but in general (e.g. functions on the integers with possible non-termination) this is impossible.


EDIT: I'm creating an interpreter for another language

Can you just keep the original program AST or source location alongside the Haskell functions you've translated them into? It seems that you want "equality" based on that.

like image 36
ephemient Avatar answered Nov 08 '22 13:11

ephemient


== requires things to be deriving Eq

Actually (==) requires an instance of Eq, not necessarily a derived instance. What you probably need to do is to provide your own instance of Eq which simply ignores the (Value -> IO Value) part. E.g.,

data D = D Int Bool (Value -> IO Value)

instance Eq D where
  D x y _ == D x' y' _ = x==x && y==y'

Does that help, maybe?

like image 6
Captain Fim Avatar answered Nov 08 '22 11:11

Captain Fim


Another way to do this is to exploit StableNames.

However, special would have to return its results inside of the IO monad unless you want to abuse unsafePerformIO.

The IORef solution requires IO throughout the construction of your structure. Checking StableNames only uses it when you want to check referential equality.

like image 4
Edward Kmett Avatar answered Nov 08 '22 12:11

Edward Kmett