Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the '<-' do in scala?

Tags:

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?
like image 663
catagon87 Avatar asked Nov 20 '13 20:11

catagon87


1 Answers

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 As and Hs 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.

like image 187
Robin Green Avatar answered Sep 28 '22 12:09

Robin Green