before 在 ML 中的用法
The usage of before in ML
ML 的前身在http://sml-family.org/Basis/general.html 中被描述为
a before b
returns a. It provides a notational shorthand for evaluating a, then b, before
returning the value of a.
当我尝试使用此命令时期望 x = 4 并且 (4+1) 被评估
val x = (3+1 before 4+1)
我收到错误消息:
Standard ML of New Jersey v110.78 [built: Sun Apr 26 01:06:11 2015]
- stdIn:1.11-1.25 Error: operator and operand don't agree [overload conflict]
operator domain: [+ ty] * unit
operand: [+ ty] * [+ ty]
in expression:
(3 + 1 before 4 + 1)
-
可能出了什么问题?
编辑
根据 Matt 的回答,我应该使用
val x = (3+1 before print "<end>")
我还发现before
用于处理一些FileIO函数后关闭流。
(* *)
val infile = "input.txt" ;
(* reading from file follow this to list of string per line *)
fun readlist (infile : string) = let
val ins = TextIO.openIn infile
fun loop ins =
case TextIO.inputLine ins of
SOME line => line :: loop ins
| NONE => []
in
loop ins before TextIO.closeIn ins
end ;
val pureGraph = readlist(infile);
size (hd pureGraph)
从 here 开始,它表示 before
的类型是 before : ('a * unit) -> 'a
,并且正如您的类型错误所指定的那样,它期望第二个参数的类型是unit
,但是,您提供了 int
类型的内容。尝试执行 val x = (3+1 before ())
,您应该会得到预期的结果。预期目的是让第二个参数成为影响计算的某种方面,例如操作 ref
单元格或执行一些 IO,您希望在评估第一个参数之前 运行。好像以下都是一样的:
val x = e1 before e2
和
val x = let val a = e1
val _ = e2
in a end
也就是说,before
不是我真正使用的东西,所以如果其他人有任何补充,当然欢迎评论。
ML 的前身在http://sml-family.org/Basis/general.html 中被描述为
a before b returns a. It provides a notational shorthand for evaluating a, then b, before returning the value of a.
当我尝试使用此命令时期望 x = 4 并且 (4+1) 被评估
val x = (3+1 before 4+1)
我收到错误消息:
Standard ML of New Jersey v110.78 [built: Sun Apr 26 01:06:11 2015]
- stdIn:1.11-1.25 Error: operator and operand don't agree [overload conflict]
operator domain: [+ ty] * unit
operand: [+ ty] * [+ ty]
in expression:
(3 + 1 before 4 + 1)
-
可能出了什么问题?
编辑
根据 Matt 的回答,我应该使用
val x = (3+1 before print "<end>")
我还发现before
用于处理一些FileIO函数后关闭流。
(* *)
val infile = "input.txt" ;
(* reading from file follow this to list of string per line *)
fun readlist (infile : string) = let
val ins = TextIO.openIn infile
fun loop ins =
case TextIO.inputLine ins of
SOME line => line :: loop ins
| NONE => []
in
loop ins before TextIO.closeIn ins
end ;
val pureGraph = readlist(infile);
size (hd pureGraph)
从 here 开始,它表示 before
的类型是 before : ('a * unit) -> 'a
,并且正如您的类型错误所指定的那样,它期望第二个参数的类型是unit
,但是,您提供了 int
类型的内容。尝试执行 val x = (3+1 before ())
,您应该会得到预期的结果。预期目的是让第二个参数成为影响计算的某种方面,例如操作 ref
单元格或执行一些 IO,您希望在评估第一个参数之前 运行。好像以下都是一样的:
val x = e1 before e2
和
val x = let val a = e1
val _ = e2
in a end
也就是说,before
不是我真正使用的东西,所以如果其他人有任何补充,当然欢迎评论。