Note that there are some explanatory texts on larger screens.

plurals
  1. POIn Scala, what does "extends (A => B)" on a case class mean?
    primarykey
    data
    text
    <p>In researching how to do Memoization in Scala, I've found some code I didn't grok. I've tried to look this particular "thing" up, but don't know by what to call it; i.e. the term by which to refer to it. Additionally, it's not easy searching using a symbol, ugh!</p> <p>I saw the following code to do memoization in Scala <a href="https://stackoverflow.com/questions/16257378/is-there-a-generic-way-to-memoize-in-scala">here</a>: </p> <pre><code>case class Memo[A,B](f: A =&gt; B) extends (A =&gt; B) { private val cache = mutable.Map.empty[A, B] def apply(x: A) = cache getOrElseUpdate (x, f(x)) } </code></pre> <p>And it's what the case class is extending that is confusing me, the <code>extends (A =&gt; B)</code> part. First, what is happening? Secondly, why is it even needed? And finally, what do you call this kind of inheritance; i.e. is there some specific name or term I can use to refer to it?</p> <p>Next, I am seeing Memo used in this way to calculate a Fibanocci number <a href="https://github.com/pathikrit/scalgos/blob/master/src/main/scala/com/github/pathikrit/scalgos/Combinatorics.scala" rel="nofollow noreferrer">here</a>: </p> <pre><code> val fibonacci: Memo[Int, BigInt] = Memo { case 0 =&gt; 0 case 1 =&gt; 1 case n =&gt; fibonacci(n-1) + fibonacci(n-2) } </code></pre> <p>It's probably my not seeing all of the "simplifications" that are being applied. But, I am not able to figure out the end of the <code>val</code> line, <code>= Memo {</code>. So, if this was typed out more verbosely, perhaps I would understand the "leap" being made as to how the Memo is being constructed.</p> <p>Any assistance on this is greatly appreciated. Thank you.</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