# Comparing data containing functions without crashing

**URL:** <https://discourse.elm-lang.org/t/comparing-data-containing-functions-without-crashing/5840>\
**Category:** Show and Tell\
**Created:** [May 25, 2020, 8:59pm UTC](https://discourse.elm-lang.org/t/comparing-data-containing-functions-without-crashing/5840 "2020-05-25T20:59:55Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![malaire](https://avatars.discourse-cdn.com/v4/letter/m/b782af/32.png) [@malaire](https://discourse.elm-lang.org/u/malaire)\
**Post date:** [May 25, 2020, 8:59pm UTC](https://discourse.elm-lang.org/t/comparing-data-containing-functions-without-crashing/5840/1 "2020-05-25T20:59:55Z")

</div>

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.

```auto
$ 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:

```auto
$ 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

```

---

<div class="post-metadata">

**Author:** ![opvasger](https://avatars.discourse-cdn.com/v4/letter/o/8e8cbc/32.png) [@opvasger](https://discourse.elm-lang.org/u/opvasger)\
**Post date:** [May 28, 2020, 7:07am UTC](https://discourse.elm-lang.org/t/comparing-data-containing-functions-without-crashing/5840/2 "2020-05-28T07:07:05Z")

</div>

That’s really clever! I can’t imagine this is the intended semantic tho… @evancz?

---

<div class="post-metadata">

**Author:** ![system](https://canada1.discourse-cdn.com/flex035/uploads/elm_lang/original/1X/50a05e53677a2c3b47776d7abd0f113eb50193a1.png) [@system](https://discourse.elm-lang.org/u/system)\
**Post date:** [June 7, 2020, 7:07am UTC](https://discourse.elm-lang.org/t/comparing-data-containing-functions-without-crashing/5840/3 "2020-06-07T07:07:09Z")

</div>

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.
