Pergunta

Eu posso usar um = em scala para-compreensão de textos (conforme especificado na secção 6.19 do SLS) como segue:

Opção

Suponha que eu tenha alguma função String => Option[Int]:

scala> def intOpt(s: String) = try { Some(s.toInt) } catch { case _ => None }
intOpt: (s: String)Option[Int]

Então eu posso usá-lo assim

scala> for {
   |     str <- Option("1")
   |     i <- intOpt(str)
   |     val j = i + 10    //Note use of = in generator
   |   }
   |   yield j
res18: Option[Int] = Some(11)

Foi o meu entendimento de que esta era essencialmente equivalente a:

scala> Option("1") flatMap { str => intOpt(str) } map { i => i + 10 } map { j => j }
res19: Option[Int] = Some(11)

Isto é, incorporado gerador foi uma maneira de injetar uma map em uma sequência de flatMap chamadas.Tão longe, tão bom.

Qualquer um.RightProjection

O que eu realmente quero fazer: use um semelhante para a compreensão de como o exemplo anterior utilizando a Either monad.

No entanto, se podemos usá-lo em um semelhante cadeia, mas desta vez usando o Either.RightProjection mônada/functor, isso não funciona:

scala> def intEither(s: String): Either[Throwable, Int] = 
  |      try { Right(s.toInt) } catch { case x => Left(x) }
intEither: (s: String)Either[Throwable,Int]

Então use:

scala> for {
 | str <- Option("1").toRight(new Throwable()).right
 | i <- intEither(str).right //note the "right" projection is used
 | val j = i + 10
 | }
 | yield j
<console>:17: error: value map is not a member of Product with Serializable with Either[java.lang.Throwable,(Int, Int)]
              i <- intEither(str).right
                ^

O problema tem algo a ver com a função que o direito de projecção de espera como um argumento para a sua flatMap método (por exemplo,ele espera que uma R => Either[L, R]).Mas a modificação não chamar right no segundo gerador, ele ainda não vai compilar.

scala>  for {
 |        str <- Option("1").toRight(new Throwable()).right
 |        i <- intEither(str) // no "right" projection
 |          val j = i + 10
 |      }
 |      yield j
<console>:17: error: value map is not a member of Either[Throwable,Int]
              i <- intEither(str)
                            ^

Mega Confusão

Mas agora eu fico duplamente confusa.A seguir funciona perfeitamente:

scala> for {
 |       x <- Right[Throwable, String]("1").right
 |       y <- Right[Throwable, String](x).right //note the "right" here
 |     } yield y.toInt
res39: Either[Throwable,Int] = Right(1)

Mas isso não:

scala> Right[Throwable, String]("1").right flatMap { x => Right[Throwable, String](x).right } map { y => y.toInt }
<console>:14: error: type mismatch;
 found   : Either.RightProjection[Throwable,String]
 required: Either[?,?]
              Right[Throwable, String]("1").right flatMap { x => Right[Throwable, String](x).right } map { y => y.toInt }
                                                                                             ^

Eu pensei que estes eram equivalentes

  • O que está acontecendo?
  • Como posso incorporar um = gerador de uma compreensão, através de um Either?
Foi útil?

Solução

O fato de que você não pode incorporar o = no para-a compreensão está relacionado com esse problema relatado por Jason Zaugg;a solução é Certo viés Either (ou crie um novo tipo de dados isomórficas para ele).

Para o seu mega-confusão, expandiu o açúcar incorretamente.O desugaring de

for {
  b <- x(a)
  c <- y(b)
} yield z(c)

é

x(a) flatMap { b =>
 y(b) map { c =>
  z(c) }} 

e não

x(a) flatMap { b => y(b)} map { c => z(c) }

Portanto, você deve ter feito isso:

scala> Right[Throwable, String]("1").right flatMap { x => Right[Throwable, String](x).right map { y => y.toInt } }
res49: Either[Throwable,Int] = Right(1)

Mais divertido sobre desugaring (o `j = i + 10` problema)

for {
  b <- x(a)
  c <- y(b)
  x1 = f1(b)
  x2 = f2(b, x1)
  ...
  xn = fn(.....)
  d <- z(c, xn)
} yield w(d)

é desugared em

x(a) flatMap { b =>
  y(b) map { c =>
    x1 = ..
    ...
    xn = ..
    (c, x1, .., xn) 
  } flatMap { (_c1, _x1, .., _xn) =>
    z(_c1, _xn) map w }}

Então, no seu caso, y(b) tem o tipo de resultado Either o que não tem map definidos.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top