我是 SML 初学者,刚刚编写我的第一个函数。
该函数应该生成不包含零的自然数对的流。
此函数使用带有谓词的过滤器来删除其成员之一为零的对,会产生语法错误:
fun nat_pairs_not_zero () = filters not_zero nat_pairs();
stdIn:56.20-59.1 Error: operator and operand don't agree [tycon mismatch]
operator domain: (int * int) sequ
operand: unit -> (int * int) sequ
in expression:
(filters nicht_null) nat_pairs
如果我首先执行 nat_pairs 并存储其结果并仅使用结果,它就会起作用。
fun nat_pairs_not_zero () = let
val lst = nat_pairs()
in
filters not_null lst
end;
如果我在 nat_pairs
周围添加额外的大括号,它也可以工作。
fun nat_pairs_not_zero () = filters not_zero (nat_pairs());
如果我只执行 (nat_pairs())
和 nat_pairs()
,两者都会给我相同的输出:
val x = CONS ((0,0),fn) : (int * int) sequ
有人可以解释一下带大括号和不带大括号的版本之间的区别吗?
需要尝试的函数定义
type ’a lazy = unit -> ’a;
fun force (f:’a lazy) = f ();
datatype ’a sequ = NIL
| CONS of ’a * ’a sequ lazy;
fun filters p NIL = NIL
| filters p (CONS (x,r)) =
if p x then CONS (x,fn ()=>filters p (force r))
else filters p (force r);
fun next_pair (x,0) = CONS ((0,x+1), fn ()=>next_pair((0,x+1)))
| next_pair (x, y) = CONS ((x+1,y-1), fn ()=>next_pair(x+1,y-1));
fun nat_pairs () = CONS ( (0,0), fn()=>next_pair((0,0)));
fun not_zero (0,b) = false
| not_zero (a,0) = false
| not_zero (a,b) = true;
最佳答案
请注意,空格是无关紧要的,因此
filters not_zero nat_pairs()
与
相同filters not_zero nat_pairs ()
由于应用程序关联到左侧,因此将括号括起来为
((filters not_zero) nat_pairs) ()
因此,()
是 filters
的第三个参数,而不是 nat_pairs
的第三个参数。
关于sml - 参数列表中 nat_pairs() 和 (nat_pairs()) 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16385784/