Note that there are some explanatory texts on larger screens.

plurals
  1. POUnintuitive type signature in Haskell
    primarykey
    data
    text
    <p>I made this (what I thought to be) fairly straightforward code to calculate the third side of a triangle:</p> <pre><code>toRadians :: Int -&gt; Double toRadians d = let deg = mod d 360 in deg/180 * pi lawOfCosines :: Int -&gt; Int -&gt; Int -&gt; Double lawOfCosines a b gamma = sqrt $ a*a + b*b - 2*a*b*(cos (toRadians gamma)) </code></pre> <p>However, when I tried to load it into GHCi, I got the following errors:</p> <pre><code>[1 of 1] Compiling Main ( law_of_cosines.hs, interpreted ) law_of_cosines.hs:3:18: Couldn't match expected type `Double' with actual type `Int' In the first argument of `(/)', namely `deg' In the first argument of `(*)', namely `deg / 180' In the expression: deg / 180 * pi law_of_cosines.hs:6:26: No instance for (Floating Int) arising from a use of `sqrt' Possible fix: add an instance declaration for (Floating Int) In the expression: sqrt In the expression: sqrt $ a * a + b * b - 2 * a * b * (cos (toRadians gamma)) In an equation for `lawOfCosines': lawOfCosines a b gamma = sqrt $ a * a + b * b - 2 * a * b * (cos (toRadians gamma)) law_of_cosines.hs:6:57: Couldn't match expected type `Int' with actual type `Double' In the return type of a call of `toRadians' In the first argument of `cos', namely `(toRadians gamma)' In the second argument of `(*)', namely `(cos (toRadians gamma))' </code></pre> <p>It turns out the fix was to remove my type signatures, upon which it worked fine.</p> <pre><code>toRadians d = let deg = mod d 360 in deg/180 * pi lawOfCosines a b gamma = sqrt $ a*a + b*b - 2*a*b*(cos (toRadians gamma)) </code></pre> <p>And when I query the type of <code>toRadians</code> and <code>lawOfCosines</code>:</p> <pre><code>*Main&gt; :t toRadians toRadians :: (Floating a, Integral a) =&gt; a -&gt; a *Main&gt; :t lawOfCosines lawOfCosines :: (Floating a, Integral a) =&gt; a -&gt; a -&gt; a -&gt; a *Main&gt; </code></pre> <p>Can someone explain to me what's going on here? Why the "intuitive" type signatures I had written were in fact incorrect?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    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