|
|
|
|
|
by amadiver
5644 days ago
|
|
I'm trying to parse all of this, but my understanding of Scala is shaky. Could anyone explain this statement -- I think it'd help a lot: sealed trait Option[+A] {
def bind[B](f: A => Option[B]): Option[B]
(My best guess: define a trait named `Option` ... something about an object of type A ... really not sure of the +. Then define a function `bind` that ... something about type `B` ... which takes an argument of type `f`? and returns the argument wrapped in an Option?) |
|
the Option type defines a method `bind` (I'll come back to the type B) which takes a function f that takes something of type A and returns something of type Option[B], no matter what B is (Scala makes you declare the type parameters you use in a function's arguments in the beginning (after its name)).
I found that explaining bind works best with a more familiar type like List.
if we have a type List of A's, and to simplify further, let's say that A is Int, so we have a List of Ints, then bind is a function that applies its argument, the latter being a function itself, on all its elements, and merging the resulting lists together. Suppose we pass the function `f` that for an Int returns the int itself and its double to the bind function of the following list: [1, 10, 100]
In the first step, the function f is applied to all the list elements: [[1, 2], [10, 20], [100, 200]] Than flattens it so we end up with: [1, 2, 10, 20, 100, 200].