zero_coding zero_coding - 2 years ago 212
Scala Question

Where are the other results

I have following applicative definition and implementation:

import simulacrum._

@typeclass trait Applicative[F[_]] {

def pure[A](a: A): F[A]

def apply[A, B](fa: F[A])(ff: F[A => B]): F[B]

def map[A,B](fa: F[A])(f: A => B): F[B] =
apply(fa)(pure(f))

}

object Applicative {

implicit val optionApplicative: Applicative[Option] = new Applicative[Option] {
def pure[A](a: A): Option[A] = Some(a)

def apply[A, B](fa: Option[A])(ff: Option[A => B]): Option[B] = (fa, ff) match {
case (None, _) => None
case (Some(_), None) => None
case (Some(a), Some(f)) => Some(f(a))
}

}

implicit val listApplicative: Applicative[List] = new Applicative[List] {
def pure[A](a: A): List[A] = List(a)

def apply[A, B](fa: List[A])(ff: List[A => B]): List[B] =
(fa zip ff).map { case (a, f) => f(a) }

}

}


When I execute map on the list:

Applicative[List].map(List(1,2,3))(_ + 1)


I've got:

res2: List[Int] = List(2)


But I do expect
List(2,3,4)
. What am I doing wrong?

Answer Source
def apply[A, B](fa: List[A])(ff: List[A => B]): List[B] =
  (fa zip ff).map { case (a, f) => f(a) }

This is caused by your ff size is 1 by def pure[A](a: A): List[A] = List(a).

So:

(fa zip ff).map { case (a, f) => f(a) }

=>:

List(1, 2, 3) zip List(f).map { case (a, f) => f(a) }

=>:

List((1, f)).map { case (a, f) => f(a) }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download