Functional programming 实现懒惰和记忆

Functional programming 实现懒惰和记忆,functional-programming,sml,smlnj,Functional Programming,Sml,Smlnj,在《纯粹功能数据结构》一书中,懒惰是一块基石,但没有明确描述他是如何获得它的,至少对我来说是这样。 我想我只需要写: 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: inserti

在《纯粹功能数据结构》一书中,懒惰是一块基石,但没有明确描述他是如何获得它的,至少对我来说是这样。 我想我只需要写:

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)=$(打印“评估…”\n;强制x+强制y)

但是用
plus($4,$5)
调用它会对它进行评估,并且不会对它进行记忆,因为它返回
$9
,而不是
$plus(强制$4,强制$5)
,并且它会同时打印
评估…

- plus ($4, $5);;
Evaluating...
val it = $ 9 : int susp
- plus ($4, $5);;
Evaluating...
val it = $ 9 : int susp

我还想获得关键字
lazy
,但我不确定SML NewJersey是否支持此功能,它是由Chris Okasaki实现的,还是手动删除的。 关键字在我的编辑器中突出显示,但在编写时

fun lazy plus($x,$y)=$(x+y)

我得到的
lazy
是采用两个参数
加上
($x,$y)
的函数,类型如下:

val lazy=fn:'a->int-susp*int-susp->int-susp



我的问题归结为如何在新泽西州SML获得懒惰和记忆?

您需要启用懒惰并添加一些括号(书中的
$
有特殊的解析规则):


请注意,这不会记忆
加上

这是有效的!
plus
功能未被记忆,但暂停是,例如,
fun lazy delayed($x)=$(打印“evaluation…\n;x)
,然后将其与
val x=delayed($5)
绑定,并强制执行两次
强制执行x;强制x
仅打印一次。非常感谢。然而,我不明白为什么
x=$(案例x的($q)=>(打印“评估…\n;q))
不起作用。将其绑定为
val q=delayed($4)
时,它在被强制执行之前已打印(但仍会被记忆)。但是我想知道为什么打印没有暂停。你能详细说明一下为什么
Control.lazysml:=true
open Lazy
都是必需的,它们是做什么的吗?前者在编译器中启用Lazy求值<代码>打开懒惰
打开
Lazy
模块,以便您可以使用非限定名称。(另外,请注意,
lazy
不是一个函数。)
Standard ML of New Jersey v110.83 [built: Thu May 31 09:04:19 2018]
- Control.lazysml := true;
[autoloading]
[ ... boring details ...] 
[autoloading done]
val it = () : unit
- open Lazy;
[autoloading]
[autoloading done]
opening Lazy

  datatype 'a susp = $ of 'a
- fun plus (x, y) = $(case (x, y) of ($m, $n) => m + n);
val plus = fn : int susp * int susp -> int susp
-  val x = plus($4, $5);
val x = $$ : int susp
- fun force ($x) = x;
val force = fn : 'a susp -> 'a
- force x;
val it = 9 : int
- fun lazy plus ($x, $y) = $ (x + y);
val plus = fn : int susp * int susp -> int susp
val plus_ = fn : int susp * int susp -> int