Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The most obvious way:</p> <pre><code>type Num = { def +(a: Num): Num def *(a: Num): Num } def pyth[A &lt;: Num](a: A, b: A)(sqrt: A=&gt;A) = sqrt(a * a + b * b) // usage pyth(3, 4)(Math.sqrt) </code></pre> <p>This is horrible for many reasons. First, we have the problem of the recursive type, <code>Num</code>. This is only allowed if you compile this code with the <code>-Xrecursive</code> option set to some integer value (5 is probably more than sufficient for numbers). Second, the type <code>Num</code> is structural, which means that any usage of the members it defines will be compiled into corresponding reflective invocations. Putting it mildly, this version of <code>pyth</code> is obscenely inefficient, running on the order of several <em>hundred thousand</em> times slower than a conventional implementation. There's no way around the structural type though if you want to define <code>pyth</code> for <em>any</em> type which defines <code>+</code>, <code>*</code> and for which there exists a <code>sqrt</code> function.</p> <p>Finally, we come to the most fundamental issue: it's over-complicated. Why bother implementing the function in this way? Practically speaking, the only types it will ever need to apply to are real Scala numbers. Thus, it's easiest just to do the following:</p> <pre><code>def pyth(a: Double, b: Double) = Math.sqrt(a * a + b * b) </code></pre> <p>All problems solved! This function is usable on values of type <code>Double</code>, <code>Int</code>, <code>Float</code>, even odd ones like <code>Short</code> thanks to the marvels of implicit conversion. While it is true that this function is technically less flexible than our structurally-typed version, it is <em>vastly</em> more efficient and eminently more readable. We may have lost the ability to calculate the Pythagrean theorem for unforeseen types defining <code>+</code> and <code>*</code>, but I don't think you're going to miss that ability.</p>
    singulars
    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.
    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