I’m new to scala and most functional languages and I’m currently trying to factor a number. i’ve written the code:
lazy val factors = for(int <- 2 until math.ceil(math.sqrt(number)).toInt if number%int == 0) yield int
I was wondering If I declared the scala val as lazy will it not evaluate the entire for comprehension when I call factors.head?
Your
factorsvariable is lazy; theforcomprehension isn’t. When you accessfactorsthe first time, yourforcomprehension will be fully evaluated.In Scala,
forcomprehension is merely a sugar forflatMap,map, andwithFiltermethod calls. So if your backing data structure is strict (such asRange– which is what you are using), yourforcomprehension will also be strict. If the data structure is lazy (such asStream), so will beforcomprehension.Observe the difference: