marcin_j
marcin_j

Reputation: 444

for expression in scala

Grr... I am really banging my head on the table wondering why this doesn't work. Could some please enlighten me?

type Occurrences = List[(Char, Int)]

def generateSubsets( occ: Occurrences ): Occurrences = {
    if (occ.isEmpty) List()
    else {
        val firstChar = occ.head._1
        val firstCharOcc: Int = occ.head._2
        val comb = for( i <- (1 to firstCharOcc); sp <- generateSubsets( occ.tail) ) 
                          yield (firstChar, i)::sp
        comb.toList
    }
}

Eclipse underlines the line with the for expression and tells me that "value :: is not a member of (Char, Int)"...

But when I do this:

val occ = List(('a', 5), ('b', 3), ('l', 2))

val t = ('m', 4)::occ

everything works swimmingly.

Upvotes: 1

Views: 108

Answers (2)

Gennadiy
Gennadiy

Reputation: 326

The error is because of sp <- generateSubsets( occ.tail) statement. generateSubsets returns a List just like you think, but then when you "assign" it to sp, sp is actually (Char, Int) instance during each iteration. Therefore you cannot have ('a', 5) :: sp because it is equivalent to ('a', 5) :: ('b', 3). To help you understand what is going on try this simple code

  def test() = {
    val i = 3
    val occ = List(('a', 1), ('b', 2))
    for( i <- (1 to i); sp <- ( occ) )
      println(i, sp)
  }

  test()

and look at the result

Upvotes: 2

Sergii Lagutin
Sergii Lagutin

Reputation: 10681

At this line for( i <- (1 to firstCharOcc); sp <- generateSubsets( occ.tail) ) you iterate wtih variable sp over list of tuples returned by generateSubsets. So sp type is also (Char, Int). At the end of for iteration you try join two tuples (Char, Int) into list with method :: which is not member of these tuples.

Upvotes: 1

Related Questions