- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
假设我正在尝试通过一个操作来实现一种非常简单的领域特定语言:
printLine(line)
n
的程序作为输入,如果
n
打印一些东西可被 10k 整除,然后用
n + 1
调用自身, 直到
n
达到某个最大值
N
.
@annotation.tailrec def p(n: Int): Unit = {
if (n % 10000 == 0) printLine("line")
if (n > N) () else p(n + 1)
}
import scalaz._
object Demo1 {
// define operations of a little domain specific language
sealed trait Lang[X]
case class PrintLine(line: String) extends Lang[Unit]
// define the domain specific language as the free monad of operations
type Prog[X] = Free[Lang, X]
import Free.{liftF, pure}
// lift operations into the free monad
def printLine(l: String): Prog[Unit] = liftF(PrintLine(l))
def ret: Prog[Unit] = Free.pure(())
// write a program that is just a loop that prints current index
// after every few iteration steps
val mod = 100000
val N = 1000000
// straightforward syntax: deadly slow, exits with OutOfMemoryError
def p0(i: Int): Prog[Unit] = for {
_ <- (if (i % mod == 0) printLine("i = " + i) else ret)
_ <- (if (i > N) ret else p0(i + 1))
} yield ()
// Same as above, but written out without `for`
def p1(i: Int): Prog[Unit] =
(if (i % mod == 0) printLine("i = " + i) else ret).flatMap{
ignore1 =>
(if (i > N) ret else p1(i + 1)).map{ ignore2 => () }
}
// Same as above, with `map` attached to recursive call
def p2(i: Int): Prog[Unit] =
(if (i % mod == 0) printLine("i = " + i) else ret).flatMap{
ignore1 =>
(if (i > N) ret else p2(i + 1).map{ ignore2 => () })
}
// Same as above, but without the `map`; performs ok.
def p3(i: Int): Prog[Unit] = {
(if (i % mod == 0) printLine("i = " + i) else ret).flatMap{
ignore1 =>
if (i > N) ret else p3(i + 1)
}
}
// Variation of the above; Ok.
def p4(i: Int): Prog[Unit] = (for {
_ <- (if (i % mod == 0) printLine("i = " + i) else ret)
} yield ()).flatMap{ ignored2 =>
if (i > N) ret else p4(i + 1)
}
// try to use the variable returned by the last generator after yield,
// hope that the final `map` is optimized away (it's not optimized away...)
def p5(i: Int): Prog[Unit] = for {
_ <- (if (i % mod == 0) printLine("i = " + i) else ret)
stopHere <- (if (i > N) ret else p5(i + 1))
} yield stopHere
// define an interpreter that translates the programs into Trampoline
import scalaz.Trampoline
type Exec[X] = Free.Trampoline[X]
val interpreter = new (Lang ~> Exec) {
def apply[A](cmd: Lang[A]): Exec[A] = cmd match {
case PrintLine(l) => Trampoline.delay(println(l))
}
}
// try it out
def main(args: Array[String]): Unit = {
println("\n p0")
p0(0).foldMap(interpreter).run // extremely slow; OutOfMemoryError
println("\n p1")
p1(0).foldMap(interpreter).run // extremely slow; OutOfMemoryError
println("\n p2")
p2(0).foldMap(interpreter).run // extremely slow; OutOfMemoryError
println("\n p3")
p3(0).foldMap(interpreter).run // ok
println("\n p4")
p4(0).foldMap(interpreter).run // ok
println("\n p5")
p5(0).foldMap(interpreter).run // OutOfMemory
}
}
p0
)似乎运行时有某种 O(N^2) 开销,并因 OutOfMemoryError 崩溃。问题似乎是
for
-comprehension 附加
map{x => ()}
在递归调用
p0
之后,这会强制
Free
monad 用“完成'p0'然后什么都不做”的提醒来填充整个内存。
for
领悟,写出最后
flatMap
明确地(如在
p3
和
p4
中),那么问题就会消失,一切运行顺利。然而,这是一个非常脆弱的解决方法:如果我们简单地附加一个
map(id)
,程序的行为就会发生巨大的变化。到它,还有这个
map(id)
甚至在代码中都不可见,因为它是由
for
自动生成的。 -理解。
suspend
中。 .这是
Applicative
的尝试实例和
suspend
:
import scalaz._
// Essentially same as in `Demo1`, but this time with
// an `Applicative` and an explicit `Suspend` in the
// `for`-comprehension
object Demo2 {
sealed trait Lang[H]
case class Const[H](h: H) extends Lang[H]
case class PrintLine[H](line: String) extends Lang[H]
implicit object Lang extends Applicative[Lang] {
def point[A](a: => A): Lang[A] = Const(a)
def ap[A, B](a: => Lang[A])(f: => Lang[A => B]): Lang[B] = a match {
case Const(x) => {
f match {
case Const(ab) => Const(ab(x))
case _ => throw new Error
}
}
case PrintLine(l) => PrintLine(l)
}
}
type Prog[X] = Free[Lang, X]
import Free.{liftF, pure}
def printLine(l: String): Prog[Unit] = liftF(PrintLine(l))
def ret: Prog[Unit] = Free.pure(())
val mod = 100000
val N = 2000000
// try to suspend the entire second generator
def p7(i: Int): Prog[Unit] = for {
_ <- (if (i % mod == 0) printLine("i = " + i) else ret)
_ <- Free.suspend(if (i > N) ret else p7(i + 1))
} yield ()
// try to suspend the recursive call
def p8(i: Int): Prog[Unit] = for {
_ <- (if (i % mod == 0) printLine("i = " + i) else ret)
_ <- if (i > N) ret else Free.suspend(p8(i + 1))
} yield ()
import scalaz.Trampoline
type Exec[X] = Free.Trampoline[X]
val interpreter = new (Lang ~> Exec) {
def apply[A](cmd: Lang[A]): Exec[A] = cmd match {
case Const(x) => Trampoline.done(x)
case PrintLine(l) =>
(Trampoline.delay(println(l))).asInstanceOf[Exec[A]]
}
}
def main(args: Array[String]): Unit = {
p7(0).foldMap(interpreter).run // extremely slow; OutOfMemoryError
p8(0).foldMap(interpreter).run // same...
}
}
suspend
没有真正的帮助:它仍然很慢,并且崩溃了
OutOfMemoryError
s。
suspend
以某种方式不同?
map
的情况下使用 for-comprehensions。到底?
最佳答案
那个多余的map
Scala 编译器添加的将递归从尾部位置移动到 非尾位置。 Free monad 仍然使这个堆栈安全,但空间复杂度变为 O(N) 而不是 O(1)。 (具体来说,它仍然不是 O(N2)。)
是否可以制作scalac
优化 map
离开是一个单独的问题(我不知道答案)。
我将尝试说明解释时发生了什么p1
与 p3
. (我将忽略对 Trampoline
的翻译,这是多余的(见下文)。)p3
(即没有额外的 map
)
让我使用以下速记:
def cont(i: Int): Unit => Prg[Unit] =
ignore1 => if (i > N) ret else p3(i + 1)
p3(0)
解释如下
p3(0)
printLine("i = " + 0) flatMap cont(0)
// side-effect: println("i = 0")
cont(0)
p3(1)
ret flatMap cont(1)
cont(1)
p3(2)
ret flatMap cont(2)
cont(2)
p1
(即额外的
map
)
def cont(i: Int): Unit => Prg[Unit] =
ignore1 => (if (i > N) ret else p1(i + 1)).map{ ignore2 => () }
def cpu: Unit => Prg[Unit] = // constant pure unit
ignore => Free.pure(())
p1(0)
解释如下:
p1(0)
printLine("i = " + 0) flatMap cont(0)
// side-effect: println("i = 0")
cont(0)
p1(1) map { ignore2 => () }
// Free.map is implemented via flatMap
p1(1) flatMap cpu
(ret flatMap cont(1)) flatMap cpu
cont(1) flatMap cpu
(p1(2) map { ignore2 => () }) flatMap cpu
(p1(2) flatMap cpu) flatMap cpu
((ret flatMap cont(2)) flatMap cpu) flatMap cpu
(cont(2) flatMap cpu) flatMap cpu
((p1(3) map { ignore2 => () }) flatMap cpu) flatMap cpu
((p1(3) flatMap cpu) flatMap cpu) flatMap cpu
(((ret flatMap cont(3)) flatMap cpu) flatMap cpu) flatMap cpu
N
.我们只是将评估从堆栈移到了堆。
Free
内存友好,将递归保持在“尾部位置”,即
flatMap
的右侧(或
map
)。
Trampoline
没有必要,因为
Free
已经蹦床了。您可以直接翻译到
Id
并使用
foldMapRec
对于堆栈安全解释:
val idInterpreter = new (Lang ~> Id) {
def apply[A](cmd: Lang[A]): Id[A] = cmd match {
case PrintLine(l) => println(l)
}
}
p0(0).foldMapRec(idInterpreter)
关于scala - 免费 ~> 蹦床 : recursive program crashes with OutOfMemoryError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41123032/
虽然我在理解递归方面没有任何问题,但我似乎无法理解汉诺塔问题的递归解决方案。这是来自 Wikipedia 的代码: procedure Hanoi(n: integer; source, dest,
虽然我在理解递归方面没有任何问题,但我似乎无法理解汉诺塔问题的递归解决方案。这是来自 Wikipedia 的代码: procedure Hanoi(n: integer; source, dest,
The Third Commandment的 The Little Schemer状态: When building a list, describe the first typical elemen
编辑 有关映射递归的“正确”Groovy 式方法,请参阅下面的@tim 解决方案。由于 Map findRecursive 在 Groovy 中尚不存在,如果您发现自己在应用程序的各个部分都需要此功能
这是尝试求解 3*3 的线性方程并打印结果,但在注释行中遇到了问题: 我在程序外部定义了 LinearSolution 模块,我应该在程序内部定义它吗?有什么区别? 为什么说该语句是递归的,你知道,当
我正在学习 Clojure 并从复制 Python 程序的功能开始,该程序将通过遵循(非常简单的)隐马尔可夫模型来创建基因组序列。 一开始,我坚持使用我已知的串行编程方式并大量使用 def 关键字,从
我有一个记录: type node = { content : string; parent : node option;
我发现 Java 8 已经显着清理了将文件内容读取到字符串中的过程: String contents = new String(Files.readAllBytes(Paths.get(new URI
我目前正在用 Java 编写一个图形库,我想要一个工具来可视化一些图形。我发现了 Graph-viz,它恰好是一种很好的(尽管有缺陷)做到这一点的方法。 在我的模型中,图由节点和边组成。每个节点都有一
昨天我遇到了这个pipes Common Lisp 库。它在某种程度上看起来很像 clojure 的惰性序列抽象,因此我决定使用它来实现 Common Lisp 中递归惰性斐波那契序列定义的经典(且优
昨天我遇到了这个pipes Common Lisp 库。它在某种程度上看起来很像 clojure 的惰性序列抽象,因此我决定使用它来实现 Common Lisp 中递归惰性斐波那契序列定义的经典(且优
我在开发一个递归函数时遇到了问题,该函数将查看两个列表是否彼此相等,包括查看子列表。到目前为止,我有: (defun are-equal2 (X Y) (cond ((null X) nil)
在 Abelson/Sussman 的经典著作《计算机程序的结构和解释》中,在关于树递归和斐波那契数列的第 1.2.2 节中,他们展示了这张图片: 计算第 5 个斐波那契数时生成的树递归过程 然后他们
SICP中的Section 1.2.1 中的作者在下面给出了这样的代码示例,以显示如何使用迭代过程解决阶乘问题: (define (factorial n) (fact-iter 1 1 n))
我继承了 的遗产Fortran 77 我现在的代码 试试 前往 编译 Fortran 2003 标准。我对 Fortran (我知道 C 和 Python)一无所知,我正在学习它。 下面的代码片段会导
这个警告来自哪里: Warning: `recursive` is deprecated, please use `recurse` instead 我在这里看到过:https://r-pkgs.or
Section 2.2 of the Happy user manual建议您使用左递归而不是右递归,因为右递归是“低效的”。基本上他们是说,如果您尝试解析一长串项目,右递归将溢出解析堆栈,而左递归使
问题 我有一个递归 CTE 查询,但是在创建循环时它失败了。我已经修复了简单的循环(例如 1 -> 2 -> 1),但无法修复更复杂的循环(例如 1 -> 2 -> 3 -> 2)。 查询详情 测试表
看完麻省理工学院的动态规划讲座后,我想练习一下斐波那契数列。我首先编写了朴素的递归实现,然后添加了内存。这是内存版本: package main import ( "fmt" ) func f
按照以下步骤,Cloudformation 堆栈可以进入递归锁: 在不导入值的情况下设置 CF(并创建堆栈) 使用相同的 CF 模板创建 soms 输出值(并更新堆栈) 在同一 CF 模板(和更新堆栈
我是一名优秀的程序员,十分优秀!