I’m learning Scala and have a quick question: Can someone please explain to me why the following two sets of code yield different results?
def grey0(n: Int): List[List[String]]={
if (n==0) List(Nil)
else for(i<-List("0","1"); j<-grey0(n-1)) yield i :: j
}
versus
def grey1(n: Int): List[List[String]]={
if (n==0) Nil
else for(i<-List("0","1"); j<-grey0(n-1)) yield i :: j
}
The first option yields the result I am looking for. What I don’t understand is, why does the second option just return the empty list? I would have thought the other results would cons on to it and if anything, I would get some sort of flat list rather than a List[List[String]] (which is what I want).
In your first version
grey0(0)will return a 1-element list that contains the empty list.grey0(1)will, for each element ingrey0(0)create two lists, so you get a total of two lists becausegrey0(0)contains one list. Likewisegrey0(2)will contain 4 lists because for each of the two elements ingrey0(1)it creates 2 lists.In your second version
grey0(0)will return the empty list.grey0(1)will create two lists for each element ingrey0(0). Sincegrey0(0)has 0 elements, that makes a total of0*2=0elements in the result.