标签: for-comprehension

为了理解:如何顺序运行期货

鉴于以下方法......

def doSomething1: Future[Int] = { ... }
def doSomething2: Future[Int] = { ... }
def doSomething3: Future[Int] = { ... }
Run Code Online (Sandbox Code Playgroud)

......以及以下的理解:

for {
  x <- doSomething1
  y <- doSomething2
  z <- doSomething3
} yield x + y + z
Run Code Online (Sandbox Code Playgroud)

这三种方法并行运行,但在我的情况下doSomething2必须在doSomething1完成之后运行.如何按顺序运行这三种方法?

编辑

正如Philosophus42所建议的,下面是一个可能的实现doSomething1:

def doSomething1: Future[Int] = {
  // query the database for customers younger than 40;
  // `find` returns a `Future` containing the number of matches
  customerService.find(Json.obj("age" -> Json.obj("$lt" -> …
Run Code Online (Sandbox Code Playgroud)

scala future for-comprehension

6
推荐指数
1
解决办法
2466
查看次数

Clojure For Comprehension示例

我正在使用docjure,它的select-columns函数需要一个列映射.我想抓住我的所有列而不必手动指定它.如何生成以下作为惰性无限向量序列[:A:B:C:D:E ...:AA:AB:AC ....:ZZ ......:XFD]?

clojure sequence for-comprehension

5
推荐指数
1
解决办法
1231
查看次数

Scala for-comprehension类型推断

下一个代码

  def f(chars: List[Char]): List[List[Char]] = chars match {
    case Nil => List(Nil)
    case x :: xs => for {
      v <- f(xs)
    } yield List(x) :: v
  }
Run Code Online (Sandbox Code Playgroud)

给出错误消息

- type mismatch;  found   : List[List[Any]]  required: List[List[Char]]
Run Code Online (Sandbox Code Playgroud)

请帮助我理解为什么'for'选择最一般的Any而不是Char?我应该阅读语言规范中的哪个主题?谢谢.

scala for-comprehension

5
推荐指数
2
解决办法
298
查看次数

Scala Future [选项[T]] Un Packing

在以下代码段中,

trait MyType1; trait MyType2
import scala.concurrent.Promise

val p1 = Promise[Option[MyType1]]()
val p2 = Promise[MyType2]()
Run Code Online (Sandbox Code Playgroud)

我将p1和p2传递给另一个函数,在那里我使用一个成功的Future来完成Promise.调用此函数后,我尝试读取Promise中的值:

trait Test {
  // get the Future from the promise
  val f1 = p1.future
  val f2 = p2.future

  for {
    someF1Elem <- f1
    f1Elem     <- someF1Elem
    f2Elem     <- f1Elem
  } yield {
    // do something with f1Elem and f2Elem
    "..."
  }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试编译它时,我遇到了一些编译器问题.

Error:(52, 19) type mismatch;
 found   : Option[Nothing]
 required: scala.concurrent.Future[?]
      flElem     <- someF1Elem
                  ^
Run Code Online (Sandbox Code Playgroud)

IntelliJ没有显示任何错误,也没有显示任何错误,并且类型看起来是对齐的.但我不确定编译器为什么不开心!有线索吗?

scala future promise for-comprehension

5
推荐指数
1
解决办法
2823
查看次数

如何让嵌套的 flatMap 和 map 更容易理解

假设,我们有一个 struct M

public struct M<T> {
    let value: T
    public init(_ value: T) { self.value = value }

    public func map<U>(f: T -> U) -> M<U> { return M<U>(f(value)) }
    public func flatMap<U>(f: T -> M<U>) -> M<U> { return f(value) }
}
Run Code Online (Sandbox Code Playgroud)

以及一些计算值 ( T) 并将其作为包装值返回的函数M

func task1() -> M<Int> {
    return M(1)
}

func task2(value: Int = 2) -> M<Int> {
    return M(value)
}

func task3(value: Int = 3) -> M<Int> {
    return …
Run Code Online (Sandbox Code Playgroud)

monads functional-programming for-comprehension swift

5
推荐指数
1
解决办法
562
查看次数

Scala - 意外类型从Map切换到Iterable进行理解?

为了理解地图,我对幕后打字感到困惑.我的理解是外部集合类型通常应该被保留,我们在以下两种情况下看到预期的行为:

scala> for {
     |   (k,v) <- Map(0->1,2->3)
     | } yield k -> v
res0: scala.collection.immutable.Map[Int,Int] = Map(0 -> 1, 2 -> 3)

scala> for {
     |   (k,v) <- Map(0->1,2->3)
     |   foo = 1
     | } yield k -> v
res1: scala.collection.immutable.Map[Int,Int] = Map(0 -> 1, 2 -> 3)
Run Code Online (Sandbox Code Playgroud)

但是当我在for comprehension中添加第二个作业时,我得到了一些令人惊讶的东西:

scala> for {
     |   (k,v) <- Map(0->1,2->3)
     |   foo = 1
     |   bar = 2
     | } yield k -> v
res2: scala.collection.immutable.Iterable[(Int, Int)] = List((0,1), (2,3))
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

scala for-comprehension

5
推荐指数
1
解决办法
106
查看次数

Scala Future - 用于理解、混合同步和异步

在我的method1中,我需要异步调用另一个method2,它返回Option(result1)。那么,如果 result1 为空,我需要异步调用另一个 method3,但如果 result1 不为空,我只需要返回它。

方法如下:

  def signIn(username: String): Future[User] = {
    for {
      foundUser <- userService.findByUsername(username) // this method returns Future[Option[User]], 
      // foundUser is Option[User]
      user <- if (foundUser.isEmpty) {
        val newUser = User(username = "User123")
        userService.create(newUser).map(Some(_)) // this method returns Future[Option[User]]
      }
      else
        // Here I want to return just foundUser, of course, it is not possible. 
        // IS THIS APPROACH CORRECT?? DOES THIS LINE CREATE ASYNCHRONOUS CALL?          
        Future.successful(foundUser)
    } yield user 
  }
Run Code Online (Sandbox Code Playgroud)

问题是:

Future.successful(foundUser)- 上面的代码中这种方法正确吗?此行是否创建异步调用?如果是这样,如何避免呢?我已经异步获取了 …

scala future for-comprehension

5
推荐指数
1
解决办法
844
查看次数

输入不匹配以进行理解:获取“具有可序列化的产品”

我正在编写一个函数,该函数将List[(Char, Int)]在字符串中获取一个字符出现列表 ( ),并生成该出现列表的所有子集。

所以,给定

List(('a', 2), ('b', 2))
Run Code Online (Sandbox Code Playgroud)

它会产生

List(
  List(),
  List(('a', 1)),
  List(('a', 2)),
  List(('b', 1)),
  List(('a', 1), ('b', 1)),
  List(('a', 2), ('b', 1)),
  List(('b', 2)),
  List(('a', 1), ('b', 2)),
  List(('a', 2), ('b', 2))
)
Run Code Online (Sandbox Code Playgroud)

我是这样实现的:

type Occurrences = List[(Char, Int)]

def combinations(occurrences: Occurrences): List[Occurrences] =
  if (occurrences.isEmpty) List(List())
  else for {
    (c, n) <- occurrences
    i <- n to 1 by -1
  } yield (c, i) :: combinations(occurrences.tail)
Run Code Online (Sandbox Code Playgroud)

我得到这个错误:

type mismatch;
 found   : List[List[Product with …
Run Code Online (Sandbox Code Playgroud)

types scala yield for-comprehension

5
推荐指数
1
解决办法
1830
查看次数

关于Scala的解释与Option的理解

我有以下定义:

def f: Option[String] = Some(null)
Run Code Online (Sandbox Code Playgroud)

以下评估为无:

for {x:String <- f} yield {
  x
}
Run Code Online (Sandbox Code Playgroud)

以下评估为Some(null):

for {x <- f} yield {
  x
}
Run Code Online (Sandbox Code Playgroud)

以下评估为Some(null):

f.map((x:String) => x)
Run Code Online (Sandbox Code Playgroud)

我想知道为什么它们之间存在差异?

scala for-comprehension

5
推荐指数
1
解决办法
599
查看次数

结合律失效的 monad 能否在 for-comprehension 中产生不正确的结果?

这是一个Monad实例ListT(从montrivo复制)

case class ListT[M[_], A](value: M[List[A]])
implicit def listTMonad[M[_]: Monad] = new Monad[ListT[M, *]] {
  override def flatMap[A, B](fa: ListT[M, A])(f: A => ListT[M, B]): ListT[M, B] =
    ListT(
      Monad[M].flatMap[List[A], List[B]](fa.value)(
        list => Traverse[List].flatTraverse[M, A, B](list)(a => f(a).value)
      )
    )
  override def pure[A](a: A): ListT[M, A] = ListT(Monad[M].pure(List(a)))
  override def tailRecM[A, B](a: A)(f: A => ListT[M, Either[A, B]]): ListT[M, B] = ???
}
Run Code Online (Sandbox Code Playgroud)

它并不能满足关联单子法

val a: Int => ListT[List, Int] …
Run Code Online (Sandbox Code Playgroud)

monads scala associativity for-comprehension

5
推荐指数
1
解决办法
89
查看次数