-1
  1. Can you explain me why the first definition is wrong compared to the next?

  2. Why writing ((r._2,c))._1 will fetch me penultimate element?

  3. Please give me a trace how elements are inserted in (r,c) or their significance.

Here is the code:

scala> def penpen [A] (list:List[A]):A = {
  list.foldLeft( (list.head, list.tail.head) )((r, c) => (r,c))._1
}

8: error: type mismatch;
found   : r.type (with underlying type (A, A))
required: A
list.foldLeft( (list.head, list.tail.head) )((r, c) => (r,c))._1
                                                            ^

scala> def penpen [A] (list:List[A]):A = {
  list.foldLeft( (list.head, list.tail.head) )((r, c) =>(r._2,c))._1
}
penpen: [A](list: List[A])A
sjrd
  • 21,805
  • 2
  • 61
  • 91
Sanket_patil
  • 301
  • 1
  • 10
  • 3
    As a developer you should be able to break down the problem into smaller pieces to understand how it works. You should be also able to debug it. If you don't understand the difference between `A` and `(A,A)` learn about that first. Look at the `foldLeft` signature, put println everywhere and follow the types... – yǝsʞǝla Jan 13 '16 at 03:20

1 Answers1

2

lets look first at the signature of foldLeft:

def foldLeft[B](z: B)(f: (B, A) ⇒ B): B

So it takes one type parameter: B. When you specify the first parameter group (in your case (list.head, list.tail.head), you are fixing thing type of this parameter. The type of the argument you pass is (A,A), so now, in the signature, we can substitute (A,A) anywhere it previously said B, So rewritten, the signature of foldLeft is:

def foldLeft(z: (A,A))(f: (A,A),A => (A,A)): (A,A)

So the second parameter group takes a function which takes two arguments, a (A,A) and a A, and must return a (A,A).

The function you passed for this second parameter is:

(r, c) => (r,c)

So we bind r to the first parameter, so r will have type (A,A). We bind c to the second parameter, and it has type A, then you return the tuple (r,c), which has type ((A,A),A), however the return type of this function was supposed to be (A,A), not ((A,A),A)

stew
  • 11,276
  • 36
  • 49