sml - 参数列表中 nat_pairs() 和 (nat_pairs()) 的区别

标签 sml smlnj

我是 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/

相关文章:

binary - 如何在 SML/NJ 中进行按位与运算?

sml - SML中的 curry 匿名函数

operators - 有没有办法在 SML/NJ 中获得二元运算符的柯里化(Currying)形式?

SML 从数据类型调用函数

structure - 结构内部的签名

sml - 如何使用相对于导入器的路径从 SML 中的另一个文件导入?

sml - 如何自定义 SML/NJ 交互循环?

pattern-matching - sml 中的逻辑简化

functional-programming - 从 sml 中的整数对列表返回偶数列表

functional-programming - SML 中绑定(bind)的值(value)?