5

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.

Tamajin
  • 155
  • 5
  • Possibly due to the association of the operator, since it involves a colon on the right hand side. Try moving the underscore to the left side. – Carcigenicate Mar 02 '15 at 14:47
  • You could also just use foldLeft. – Carcigenicate Mar 02 '15 at 14:52
  • 1
    The use of the /: and :\ should be avoided in preference to the more explicit foldLeft and foldRight. You may want to read this official style guide: http://docs.scala-lang.org/style/method-invocation.html – lambdista Mar 03 '15 at 14:23

2 Answers2

4

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) _
    
Ben Reich
  • 16,222
  • 2
  • 38
  • 59
1

I played around with it, and couldn't find a configuration that works.

There's always the more explicit:

val f = List(1,2,3,4,5).foldLeft(0)_

Which is arguably neater. I'll keep poking around though.

Edit:

There's this:

val f2 = (0 /: List(1,2,3,4,5))(_: (Int,Int) => Int)
val x = f2(_+_)

But that's getting pretty ugly. Without the type annotation, it complains. That's the best I could do though.

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117