Reputation:
I am trying to create the following lift function but I am hitting a brick wall:
scala> def liftOff[A,B](f : A => B) : A => Option[B] = _.map(f)
<console>:10: error: value map is not a member of type parameter A
def liftOff[A,B](f : A => B) : A => Option[B] = _.map(f)
I thought I could denote that the type parameter A is mappable but the mappable trait is now deprecated since 2.10. If the input type of the returned function is an Option it's not a problem but that is not what I need:
scala> def liftOff[A,B](f : A => B) : Option[A] => Option[B] = _ map f
liftOff: [A, B](f: A => B)Option[A] => Option[B]
Is there a way to do this?
Upvotes: 2
Views: 104
Reputation: 375885
Another option is to lift* it to the Option type first:
scala> def liftOff[A,B](f : A => B) : A => Option[B] = Some(_) map f
liftOff: [A, B](f: A => B)A => Option[B]
scala> liftOff((x:Int) => 2.0 * x)(3)
res6: Option[Double] = Some(6.0)
*Note: Here Some
is the unit/return method lifting A to a monadic (Option) type.
Upvotes: 0
Reputation: 15074
If what you are trying to define is a method that takes a function from A to B, and returns a function from A to Option[B], then you just need to combine f with a function to enclose the result in an Option, such as:
def liftOff[A,B](f : A => B) : A => Option[B] = f andThen Option.apply
if this isn't what you meant, then you might need to edit your question to make your intent clearer.
Upvotes: 3