Note that there are some explanatory texts on larger screens.

plurals
  1. POHaskell Type Coercion
    primarykey
    data
    text
    <p>I trying to wrap my head around Haskell type coercion. Meaning, when does can one pass a value into a function without casting and how that works. Here is a specific example, but I am looking for a more general explanation I can use going forward to try and understand what is going on:</p> <pre><code>Prelude&gt; 3 * 20 / 4 15.0 Prelude&gt; let c = 20 Prelude&gt; :t c c :: Integer Prelude&gt; 3 * c / 4 &lt;interactive&gt;:94:7: No instance for (Fractional Integer) arising from a use of `/' Possible fix: add an instance declaration for (Fractional Integer) In the expression: 3 * c / 4 In an equation for `it': it = 3 * c / 4 </code></pre> <p>The type of (/) is Fractional a => a -> a -> a. So, I'm guessing that when I do "3 * 20" using literals, Haskell somehow assumes that the result of that expression is a Fractional. However, when a variable is used, it's type is predefined to be Integer based on the assignment.</p> <p>My first question is how to fix this. Do I need to cast the expression or convert it somehow? My second question is that this seems really weird to me that you can't do basic math without having to worry so much about int/float types. I mean there's an obvious way to convert automatically between these, why am I forced to think about this and deal with it? Am I doing something wrong to begin with?</p> <p>I am basically looking for a way to easily write simple arithmetic expressions without having to worry about the neaty greaty details and keeping the code nice and clean. In most top-level languages the compiler works for me -- not the other way around. </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.
 

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