0

I defined the following function along the lines of Haskell snd

def snd[T](pair: (_, T)): T = pair._2

Trying to use it with a List[ListNode[T]] doesn't compile. Why not?

list
  .reduceOption(snd)

where:

case class ListNode[T](data: T, var next: Option[ListNode[T]])(implicit ordering: Ordering[T]) extends Ordered[ListNode[T]] {...}

Error:

Type mismatch, expected: (NonInferedA1, NonInferedA1) => NonInferedA1, actual Tuple2[_, Nothing] => Nothing
Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93
Abhijit Sarkar
  • 21,927
  • 20
  • 110
  • 219
  • What is `Node`? – Andrey Tyukin Jul 22 '18 at 22:06
  • 1
    @AndreyTyukin Updated question, not sure why'd it matter though. – Abhijit Sarkar Jul 22 '18 at 22:08
  • 1
    I think it expects a function with two parameters, not one that’s a pair? – Ry- Jul 22 '18 at 22:12
  • Indeed, the definition of `ListNode` doesn't matter much... You could have constructed `List.empty[Int]`, and thereby omit any mention of `Node` or `NodeList`... Anyway: `reduceOption` needs a two-argument function. `snd` takes only one argument. – Andrey Tyukin Jul 22 '18 at 22:13
  • 1
    It works as expected with `def twoArgSnd[T](a: Any, b: T): T = b` and `reduceOption(twoArgSnd[Int])`. – Andrey Tyukin Jul 22 '18 at 22:14
  • Right, defining `def snd[T](a: _, b: T): T = b` works, If one of you care to post an answer, I'll be happy to accept it. Thanks. A question with an accepted answer also ranks higher in searches, so helpful to others later. – Abhijit Sarkar Jul 22 '18 at 22:16

1 Answers1

0

Methods reduce and reduceOption require functions with arity 2, not unary functions that take a tuple.

There is a difference between

Function1[(X, Y), Z]

and

Function2[X, Y, Z]

The first one is unary and takes a tuple, the second one is binary. Same holds for methods and their eta-expansions.

This here works as expected:

def twoArgSnd[T](a: Any, b: T): T = b 

list.reduceOption(twoArgSnd[Int])

Also related:

  1. Why is scala.collection.immutable.List[Object] not GenTraversableOnce[?]
Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93
  • 1
    It works as expected... [if you expect it to work the way it actually works](https://books.google.com/books?id=4K82efXzn10C&pg=PA72#v=onepage&q&f=false). – Daniel Wagner Jul 23 '18 at 00:28