Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Never fiddled with this stuff, but here may be two partial answers which could be enough for you. I'm afraid it's not a general solution nor a way to make <code>Dynamic</code> and instance of <code>Eq</code> (it would probably be one already if it was easy). </p> <p>But in your last comment you stated that you only wanted to compare your own types. So, partial answer 1: </p> <p>You can of course compare two <code>Dynamics</code> if you guess their type. For example:</p> <pre><code>eqInt :: Int -&gt; Int -&gt; Bool eqInt = (==) x = toDyn (3::Int) y = toDyn (3::Int) z = toDyn (4::Int) compareDynamic :: (Typeable a, Eq a) =&gt; (a -&gt; a -&gt; Bool) -&gt; Dynamic -&gt; Dynamic -&gt; Maybe Bool compareDynamic eq x y = do let dEq = toDyn eq fn1 &lt;- dynApply dEq x res &lt;- dynApply fn1 y fromDynamic res </code></pre> <p>And now:</p> <pre><code>...&gt; compareDynamic eqInt x y Just True ...&gt; compareDynamic eqInt x z Just False </code></pre> <p>However, despite the misleading polymorphic type of <code>compareDynamic</code>, you can only pass in a monomorphic comparison function. See:</p> <pre><code>...&gt; compareDynamic (==) x z Nothing </code></pre> <p>I suppose that is because the type system has no way of knowing which instance of <code>(==)</code> it should actually use here. I kept <code>compareDynamic</code> polymorphic though so you don't have to create separate functions for each type.</p> <p>Now, since you only want to compare your own types, you could just have a list of comparison functions which you try in order:</p> <pre><code>eqs = [eqMyTypeA, eqMyTypeB, eqMyTypeC] comp dynA dynB = catMaybes $ map (\eq -&gt; eq dynA dynB) eqs </code></pre> <p>And <code>[]</code> would denote two different types, <code>[Just False]</code> the same type with different values and <code>[Just True]</code> the same type and value.</p> <p>In case you have a large number of types, you can also determine the constructor before doing any comparison, (this is partial answer 2) and select the right function depending on it. It the constructors are different, you wouldn't have to try compare at all:</p> <pre><code>constructor :: Dynamic -&gt; TyCon constructor = typeRepTyCon . dynTypeRep </code></pre> <p>And have a lookup table matching constructors to equality functions.</p> <p>One closing remark: Think twice if you need this. Think thrice if you need <code>Dynamic</code> at all, most Haskell programs don't. Isn't it just Java thinking sneaking in?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload