scala 折叠是如何工作的?
how scala folding works?
我正在尝试理解以下代码,但无法理解。
如果事件不存在,它应该为事件创建一个 child 演员,否则说事件作为关联的 child 演员存在。
context.child(name).fold(create())(_ => sender() ! EventExists)
但是这里的弃牌对我来说没有意义。如果 context.child 是空的,我们就会得到创建,我理解这一点。但是如果有children我们还是要创造why?
Akka 的 child
returns 一个 Option
正如您从 Option
的 scaladoc 中看到的那样:
fold[B](ifEmpty: ⇒ B)(f: (A) ⇒ B): B Returns the result of
applying f to this scala.Option's value if the scala.Option is
nonempty. Otherwise, evaluates expression ifEmpty.
或者说得更清楚:
This (fold) is equivalent to scala.Option map f getOrElse ifEmpty.
所以 fold
的第一个参数是惰性的(按名称调用)并且仅在 Option
为空时才计算。仅当 Option
不为空时才调用第二个参数(函数)。
实验:
scala> Some(0).fold({println("1");1}){_ => println("2"); 2}
2
res0: Int = 2
scala> None.fold({println("1");1}){_ => println("2"); 2}
1
res1: Int = 1
这里有一些读物:
https://kwangyulseo.com/2014/05/21/scala-option-fold-vs-option-mapgetorelse/
一些批评这种方法的人:
http://www.nurkiewicz.com/2014/06/optionfold-considered-unreadable.html
But in Option.fold() the contract is different: folding function takes
just one parameter rather than two. If you read my previous article
about folds you know that reducing function always takes two
parameters: current element and accumulated value (initial value
during first iteration). But Option.fold() takes just one parameter:
current Option value! This breaks the consistency, especially when
realizing Option.foldLeft() and Option.foldRight() have correct
contract (but it doesn't mean they are more readable).
我正在尝试理解以下代码,但无法理解。
如果事件不存在,它应该为事件创建一个 child 演员,否则说事件作为关联的 child 演员存在。
context.child(name).fold(create())(_ => sender() ! EventExists)
但是这里的弃牌对我来说没有意义。如果 context.child 是空的,我们就会得到创建,我理解这一点。但是如果有children我们还是要创造why?
Akka 的 child
returns 一个 Option
正如您从 Option
的 scaladoc 中看到的那样:
fold[B](ifEmpty: ⇒ B)(f: (A) ⇒ B): B Returns the result of applying f to this scala.Option's value if the scala.Option is nonempty. Otherwise, evaluates expression ifEmpty.
或者说得更清楚:
This (fold) is equivalent to scala.Option map f getOrElse ifEmpty.
所以 fold
的第一个参数是惰性的(按名称调用)并且仅在 Option
为空时才计算。仅当 Option
不为空时才调用第二个参数(函数)。
实验:
scala> Some(0).fold({println("1");1}){_ => println("2"); 2}
2
res0: Int = 2
scala> None.fold({println("1");1}){_ => println("2"); 2}
1
res1: Int = 1
这里有一些读物:
https://kwangyulseo.com/2014/05/21/scala-option-fold-vs-option-mapgetorelse/
一些批评这种方法的人:
http://www.nurkiewicz.com/2014/06/optionfold-considered-unreadable.html
But in Option.fold() the contract is different: folding function takes just one parameter rather than two. If you read my previous article about folds you know that reducing function always takes two parameters: current element and accumulated value (initial value during first iteration). But Option.fold() takes just one parameter: current Option value! This breaks the consistency, especially when realizing Option.foldLeft() and Option.foldRight() have correct contract (but it doesn't mean they are more readable).