Why does this list mean it has 3 or 3 elements in scala

why does this list mean it has 3 or 3 elements in scala



maybe x, y or ys, zs is empty? why should it be a list of at least 3 items according to the teacher



source to share

2 answers

Let this expression express some context that makes the types explicit.

def foo[A](
  x: List[List[A]],
  y: List[List[A]],
  xs: A,
  ys: List[A],
  zs: List[List[List[A]]]
): List[List[List[A]]] =


Usually, if you have identifiers x

and xs

, then it xs

will have a collection type (for example, List[A]

), and x

will have a collection item type (for example, A

). This is not the case here, so I think your teacher made it more difficult than necessary by naming the variables the least.

Now, for example, call foo

with the highest possible values:

> foo(Nil, Nil, 1, Nil, Nil)
res: List[List[List[Int]]] = List(List(), List(), List(List(1)))




First, consider an operation ::

that is right-associative. Given a :: as

, add the element a

to List


, focusing on the element...

If we want to break this expression, the elements of this list will be ...

  • Element x

  • Element y

  • Element List(xs::ys)

  • Tail zs

As you can see, this expression does not concatenate lists xs

, ys

and zs

, but instead creates an element with List(xs::ys)

and adds it to zs


This ensures that the three-item list: x

, y

and List(xs::ys)

. The tail zs

can be either a list or Nil

(empty List

), this expression will contain at least 3 elements.

So the next question is what type of this List




All Articles