Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The problem here is <code>area</code>'s type signature:</p> <pre><code>area :: (Num b) =&gt; a -&gt; Area b </code></pre> <p>What it says is "give me an <code>a</code>, and I'll give you an <code>Area b</code> for <em>any</em> <code>b</code> you want; you can pick". So, for instance, I could give <code>area</code> an <code>Integer</code> and expect back an <code>Area Double</code>. Clearly, this isn't what you want!</p> <p>In this case, the error arises because you use <code>x*y</code>, which has type <em>a</em>, when <em>b</em> is expected — you have to give a value that works for <em>any</em> numeric type <em>b</em>, but you're giving a value that only works for one (<em>a</em>).</p> <p>If you changed <code>area</code>'s type to <code>a -&gt; Area Integer</code>, or such, then it would work. However, I have a feeling you want the <em>instance</em> to be able to specify what the type of the area is. For this, you'll need to use a language extension called <a href="http://www.haskell.org/haskellwiki/GHC/Type_families" rel="noreferrer"><em>type families</em></a>:</p> <pre><code>{-# LANGUAGE TypeFamilies #-} class (Num (AreaComponent a)) =&gt; Shape a where type AreaComponent a area :: a -&gt; Area (AreaComponent a) instance (Num a) =&gt; Shape (Rectangle a) where type AreaComponent (Rectangle a) = a area (Rectangle x y unit) = Area (x*y) unit </code></pre> <p>This says that for every type <em>a</em> that's an instance of <code>Shape</code>, there is an <em>associated type</em> <code>AreaComponent a</code>, representing the type of each component of its area. That type is required to be an instance of <code>Num</code> by the definition of <code>Shape</code>.</p> <p>Another thing you could do, if all your shapes take a numeric type parameter, is to make the instances be for the type constructors of each shape, rather than the full shape types themselves:</p> <pre><code>class Shape sh where area :: (Num a) =&gt; sh a -&gt; Area a instance Shape Rectangle where area (Rectangle x y unit) = Area (x*y) unit </code></pre>
    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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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