I'm new to the language and trying to figure out how to read some of the code in it. Here is the example code that I'm trying to figure out:
lazy val genHeap: Gen[H] = for{
n <- arbitrary[A]
h <- frequency((1,value(empty)),(9,genHeap))
} yield insert(n,h)
I don't quite understand what is going on:
Gen
?<-
act as an =
operator?Hello fellow Coursera student! The Principles of Reactive Programming Course is not exactly the easiest place to start to learn Scala! It is an advanced Scala course.
The type return is a Gen?
Yes, that's what the :
means. (The Gen
itself is an object, a random generator to be precise, which can produce a sequence of values, each having the same type as its type parameter - in this case, H
.)
Does the <- act as an '=' operator?
Not exactly.
and the yield statement.. as I understand, it is building a heap with each iteration by inserting a new element?
Actually it's a recursion, not an iteration... but essentially, yes.
A for..yield expression is a fancy way to write a series of map
, flatMap
and withFilter
invocations. Let's desugar it down into ordinary Scala code:
lazy val genHeap: Gen[H] = arbitrary[A].flatMap(n => frequency((1,value(empty)),(9,genHeap)).map(h => insert(n,h)))
So a H
generator (genHeap
) is one that starts by generating an arbitrary A
, then generating an arbitrary H
(an empty H
with probability 0.1, or the result of invoking genHeap
itself again with probability 0.9), and then inserting the A
into the H
to get a new H
.
These A
s and H
s are both abstract types, by the way.
Yes, I'd say this is pretty advanced stuff. If you don't even know what :
means, you're definitely starting in the wrong place.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With