I’ve seen mentioned few times that if data structure contains a function, then it can’t be safely compared, as comparison may crash.
But if data structure contains NaN
in addition to the function, so that comparison always compares NaN
before the function, then comparison will never crash.
$ elm repl
> a = (0/0, (\x -> x + 10))
> b = a
> c = (0/0, (\x -> x + 100))
> a == b
True: Bool
> a == c
False: Bool
If references are same, Elm does shallow comparison of references and returns True
. Otherwise Elm begins deep comparison starting from the first item of tuples which is NaN
. As NaN == NaN
is False
, Elm returns False
. So comparison never gets to actual functions in second item of tuple.
Simple example of an opaque type storing a function:
$ elm repl
-- SETUP
> type Func a = Func (Float, (a -> a))
> new fn = Func (0/0, fn)
> run (Func (_, fn)) x = fn x
-- CREATE FUNCTIONS
> a = new (\x -> x + 10)
> b = a
> c = new (\x -> x + 100)
-- COMPARE FUNCTIONS
> a == b
True : Bool
> a == c
False : Bool
-- RUN FUNCTIONS
> run a 1
11 : number
> run b 2
12 : number
> run c 3
103 : number