Search code examples
scalapartialfunctionfoldleft

Scala: Is it possible to get partially applied function from leftfold?


I'm currently learning Scala, and I just wondered at fold-left. Since fold-left is curried, you should be able to get a partially applied function(PAF) with a first parameter as below.

(0 /: List(1, 2, 3)) _

But actually, I've got an error.

<console>:8: error: missing arguments for method /: in trait TraversableOnce;
follow this method with `_' if you want to treat it as a partially applied function

Then I tried same thing by fold-right such as below

(List(1, 2, 3) :\ 0) _

In this way, it went correctly, and I could get a PAF such as ((Int, Int) => Int) => Int

I know I can get a PAF by using foldLeft method, but I wonder whether it is possible to express it with '/:' or not.


Solution

  • The underscore syntax does not work well with right-associative methods that take multiple parameter lists. Here are the options I see:

    1. Declare a variable type:

      val x: ((Int, Int) => Int) => Int =  0 /: List(1, 2, 3)
      
    2. Similarly, use type ascription:

      val x = (0 /: List(1,2,3)) : ((Int, Int) => Int) => Int
      
    3. Use the postfix notation:

      val x = List(1,2,3)./:(0) _
      
    4. Use the foldLeft synonym:

      val x = List(1,2,3).foldLeft(0) _