3

So this compiles:

def compress[T](list: List[T]): List[(T, Int)] =
{
    list.zipWithIndex.filter { tuple => (tuple._2 == 0) || (tuple._1 != list(tuple._2 - 1)) }
}

This does not compile:

def compress[T](list: List[T]): List[(T, Int)] =
{
    list.zipWithIndex.filter { (_._2 == 0) || (_._1 != list(_._2 - 1)) }
}

Why?

2 Answers 2

14

_ does not mean x. Instead, it means "use the next parameter in the parameter list" or "convert this method into a function object", depending on context. In your case, the second one is nonsense because you want a function of one variable but use _ three times.

Hint: use x or t. Spelling out tuple isn't likely to help anyone, and the one-letter versions are as compact as _. Better yet,

filter { case (t,i) => (i==0) || (t != list(i-1)) }
Sign up to request clarification or add additional context in comments.

1 Comment

I'd always use the case (x, y) syntax as well but t2, t3 are good substitutions as well
2

Your second example expands to:

def compress[T](list: List[T]): List[(T, Int)] =
{
    list.zipWithIndex.filter { ((x => x._2) == 0) || ((y => y._1) != list((z => z._2) - 1)) }
}

which the compiler rightly rejects as nonsensical. An call containing _ expands to a lambda around just that call, and nothing else.

1 Comment

I think the last part is actually (x => x._2 == 0) || (y => y._1 != list(z => z._2 - 1)).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.