Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to get rid of this ambiguity?
    primarykey
    data
    text
    <p>I am pretty sure this has been asked before, however I was unable to find the right answer:</p> <p>I tried to eliminate the ambiguity in the following exemplary code snippet:</p> <pre><code>{-# LANGUAGE MultiParamTypeClasses #-} class FooBar a b where foo :: a -&gt; a foo = id bar :: a -&gt; a bar = foo -- ERROR AT THIS LINE </code></pre> <p>I get an error message like so:</p> <pre><code>Ambiguous type variable `b0' in the constraint: (FooBar a b0) arising from a use of `foo' Probable fix: add a type signature that fixes these type variable(s) In the expression: foo In an equation for `bar': bar = foo </code></pre> <p>which is understandable. Note however, that I'm actually unable to follow the compiler's advice and fix the type variable in question: <code>foo</code> doesn't contain <code>b</code> type variable in its type signature. Also this doesn't work:</p> <pre><code> bar = (foo :: FooBar a b =&gt; a -&gt; a) -- ERROR, the same error message </code></pre> <p>Not even with <code>-XScopedTypeVariables</code> enabled.</p> <p>How to tell GHC which FooBar to use? Is it even possible?</p> <p><strong>EDIT</strong></p> <p>Following some answers: yes, I've heard about both functional dependencies and associated types.</p> <p>As to functional dependencies - I am looking for a way to explicitly inform GHC which instance to use (as opposed to asking it to derive the correct type all by itself). </p> <p>As to both - in the real world example that this one comes from, I actually need both of the parameters <code>a</code> and <code>b</code> to be independent.</p> <p>Again: I know this example is extremely silly, I know <code>b</code> is not used in the body of the type class, which makes no sense. This is an extreme simplification of a real world example, that actually does make sense. The real use-case involves "substitutability" of types <code>a</code> using types <code>b</code> and then "unifiability" of types <code>a</code> and <code>b</code> using types <code>c</code> and unfortunately is much longer.</p> <p><strong>EDIT(2)</strong></p> <p>Okay sorry. I think you convinced me after all that I have to refactor the code in order not to have any ill-defined functions (i.e. ones that don't contain all the independent types in their type signatures). Talking to you really helped me think this thing though. Appreciated.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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