The confusion with the "lift" features in Scala

In the book Functional Programming, Scala provides an example of "Lift" in which a function of type A => B promoted to Option[A] => Option[B] .

Here's how the elevator is implemented:

 def lift[A,B](f: A => B):Option[A] => Option[B] = _ map f 

I have a couple of confusions about this:

First, what is there? Secondly, when I remove the return type from def, expecting the output type to do its magic, I get the following exception:

 scala> def lift[A,B](f: A => B) = _ map f <console>:7: error: missing parameter type for expanded function ((x$1) => x$1.map(f)) def lift[A,B](f: A => B) = _ map f 

Can someone explain what is going on here?

thanks

+6
source share
1 answer
  • lift is a function that returns a function. The returned function cancels the value (without a name) by applying the function f to this value. An unnecessary value to be removed is called _ . You can, of course, give it a more explicit name:

     def lift[A,B](f: A => B): Option[A] => Option[B] = { value => value map f } 
  • The return type of this function (return) must be explicitly specified or implicitly defined. As written, the compiler may conclude that the return value is Option[B] (more precisely, lift returns the function Option[A] => Option[B] (explicitly specified), while this function has a return type of Option[B] (implicitly defined) ), Without this type of information, the compiler needs another indication of the type of the return type.

    Alternatively, define lift this way:

     def lift[A,B](f: A => B) = { value: Option[A] => value map f } 

    Here you explicitly specify the type for value , and the compiler can infer

    • return type of return function Option[B] , because f: A => B will display type A in B ,
    • the return type for lift must be Option[A] => Option[B] .
+10
source

Source: https://habr.com/ru/post/947914/


All Articles