jedesah
jedesah

Reputation: 3013

Scala syntax for lambda functions

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?

Upvotes: 3

Views: 1684

Answers (2)

Ptharien's Flame
Ptharien's Flame

Reputation: 3246

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.

Upvotes: 2

Rex Kerr
Rex Kerr

Reputation: 167871

_ 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)) }

Upvotes: 14

Related Questions