【发布时间】:2020-05-04 10:18:53
【问题描述】:
懒惰是Purely Functional Data Structures 一书中的基石,但没有清楚地描述他是如何获得它的,至少对我来说是这样。 我以为我只需要写:
datatype 'a susp = $ of 'a
fun force ($x) = x
fun plus (x, y) = $case (x, y) of ($m, $n) => m + n
然后我得到错误:
- use "ch4.sml";;
[opening ch4.sml]
ch4.sml:3.20 Error: syntax error: inserting ORELSE
[unexpected exception: Compile]
uncaught exception Compile [Compile: "syntax error"]
raised at: ../compiler/Parse/main/smlfile.sml:19.24-19.46
../compiler/TopLevel/interact/evalloop.sml:45.54
../compiler/TopLevel/interact/evalloop.sml:306.20-306.23
../compiler/TopLevel/interact/interact.sml:65.13-65.16
我尝试将函数修改为
fun plus (x, y) = $(print "Evaluating...\n"; force x + force y)
但是用plus ($4, $5) 调用它会评估它并且没有记住它,因为它返回$ 9 而不是$ plus(force $4, force $5) 并且两次都打印Evaluating...。
- plus ($4, $5);;
Evaluating...
val it = $ 9 : int susp
- plus ($4, $5);;
Evaluating...
val it = $ 9 : int susp
我也想获取关键字lazy,但我不确定 SML New Jersey 是否支持这个,它是由 Chris Okasaki 实现的,还是手动脱糖的。
关键字在我的编辑器中突出显示,但在编写时
fun lazy plus ($x, $y) = $ (x + y)
我知道lazy 是采用两个参数plus 和($x, $y) 的函数,由类型给出:
val lazy = fn : 'a -> int susp * int susp -> int susp
我的问题归结为如何在 SML New Jersey 中获得惰性和记忆力?
【问题讨论】:
标签: functional-programming sml smlnj