Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy is Scala's type inference not as powerful as Haskell's?
    text
    copied!<p>The type inference engine of Haskell is much more powerful than Scala's. In Haskell I rarely have to explicitly write the types whereas in Scala the types can only be inferred in expressions but not in method definitions.</p> <p>For example, see following Haskell code snippet:</p> <pre><code>size xs = loop xs 0 where loop [] acc = acc loop (_ : xs) acc = loop xs (acc+1) </code></pre> <p>It returns the size of a List. The Haskell compiler can recognize what types are used and what the function definition is. The equivalent Scala code:</p> <pre><code>def size[A]: List[A] =&gt; Int = xs =&gt; { def loop: (List[A], Int) =&gt; Int = { case (Nil, acc) =&gt; acc case (_ :: xs, acc) =&gt; loop(xs, acc+1) } loop(xs, 0) } </code></pre> <p>Or with method definitions:</p> <pre><code>def size[A](xs: List[A]) = { def loop(xs: List[A], acc: Int): Int = xs match { case Nil =&gt; acc case _ :: xs =&gt; loop(xs, acc+1) } loop(xs, 0) } </code></pre> <p>My question is: Why can't I write them like the following?</p> <pre><code>def size = xs =&gt; { def loop = { case (Nil, acc) =&gt; acc case (_ :: xs, acc) =&gt; loop(xs, acc+1) } loop(xs, 0) } </code></pre> <p>Once again with method definitions:</p> <pre><code>def size(xs) = { def loop(xs, acc) = xs match { case Nil =&gt; acc case _ :: xs =&gt; loop(xs, acc+1) } loop(xs, 0) } </code></pre> <p>Is it because nobody has implemented it yet? Is the type system of Scala not as powerful as needed for this case? Or are there other reasons?</p>
 

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