scala lifting function having with a collection as argument

170 views Asked by At

I have a class which accepts a function f: Option[Seq[Option[A]]] => Option[A]]

case class Function[A](operator: Option[Seq[Option[A]]] => Option[A], name: String, arity: Int)

What i would like is for the user of this class to be able to not have to worry about the Option framework. So the user would pass a function g: Seq[A] => A and under the hood i would lift that function. The lifting part is what i'm not being able to do.

This is what i have (using optionInstance.lift of scalaz) :

object Function {
  def apply[A](operator: Seq[A] => A) = new Function(optionInstance.lift(operator),"a", 1)
}

However this does not compile since the lift operator is returning Option[Seq[A]] instead of Option[Seq[Option[A]]]. How can this be done?

2

There are 2 answers

1
C4stor On

Here's an example of how to convert between your two prototypes :

  def f[A]: Seq[A] => A = ???

  def g[A]: Option[Seq[Option[A]]] => Option[A] = {
    {
      case None => None
      case Some(seq) if seq.exists(_.isEmpty) => None
      case Some(seq) => Some(f(seq.flatten))
    }
  }

You can use this to transform your operator

0
Othman Doghri On

If you would like to return Option[Seq[Option[A]]] you have to first transform your Seq[A] into a Seq[Option[A]] before doing the lift