N M
N M

Reputation: 9

Define a function that filters items from the lazy list of lazy list

Define a function that filters items from the lazy list of lazy list. The function is supposed to have two parameters: lazy list of lazy lists and number. Only lazy lists whose length is greater than or equal to the specified value are to remain in the result list.

Example:

lazyfilter(LazyList(LazyList(1,2,3), LazyList(2,3), LazyList(4.5) ), 3 ) 
-> LazyList( LazyList(1,2,3))

My attempt :

def lazyfilter[A](listOfLists: LazyList[LazyList[A]], filter: A): LazyList[LazyList[A]] = {
  listOfLists.filter(_.length.equals(filter))
}

println(lazyfilter(LazyList(LazyList(1,2,3), LazyList(2,3), LazyList(4.5) ), 3 ))

Any idea how to do it for greater than or equal of the specified value??

Upvotes: 0

Views: 92

Answers (1)

Guru Stron
Guru Stron

Reputation: 142203

Just declare filter parameter as Int. Also potentially you don't want to evaluate the whole list, taking up to filter is enough to filter by length:

def lazyfilter[A](listOfLists: LazyList[LazyList[A]], filter: Int): LazyList[LazyList[A]] = {
  listOfLists.filter(_.take(filter).length == filter)
}

Upvotes: 1

Related Questions