scalascalazscalaz7

How to implement a Scalaz Applicative?


I have a customer type QueryResult which is

type QueryResult[A] = A org.scalactic.Or One[Error]

When doing multiple queries, I get a List[QueryResult[A]], but I want a QueryResult[List[A]]. I can implement a sequence method for Lists but I would like a more generic one, so I tried creating one with Scalaz.

def sequence2[A, T[_]: Traverse](traversable: T[QueryResult[A]])
    (implicit app: Applicative[QueryResult]): QueryResult[T[A]] = {
  app.sequence(traversable)
}

This seems to work but does not compile because there is no implicit parameter app for an Applicative[QueryResult].

How do I create one? Or can Scalaz somehow 'magically' generate one somehow?


Solution

  • This should work :

    import scalaz.Applicative
    
    implicit val queryApplicative: Applicative[QueryResult] = 
      new Applicative[QueryResult] {
        def point[A](a: => A): QueryResult[A] = Good(a)
        def ap[A, B](fa: => QueryResult[A])(f: => QueryResult[A => B]): QueryResult[B] = 
          f.flatMap(ff => fa.map(ff))
      }
    

    I also don't think you need to define sequence2 yourself, you should be able to do :

    import scalaz.std.list._
    import scalaz.syntax.traverse._
    
    List(1.point[QueryResult], 2.point[QueryResult]).sequence