简体   繁体   中英

What does the '<-' do in scala?

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:

  • The return type is Gen ?
  • Does the <- act as an = operator?
  • Is the yield statement building a heap with each iteration by inserting a new element?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM