我对我定义的 pop() 标准函数和 myPop() 函数以及相关的返回类型有一些疑问。
1.
fun myPop(L)= if null L then raise EmptyList else (hd L,tl L)
val myPop = fn:'a list ->'a*'a list
if i want to retrive the value and the list i can write:
val c=myPop([1,2,3]);
val val1=#1(c);
val val2=#2(c);
所以 val1=1 且 val2=[2,3]。
2.当我使用标准 pop() 时,我得到:
val L=[1,2,3]
pop(L);
val it = SOME (1,[2,3]) : (int * int list) option
问题是,myPop() 是一个正确的函数吗?如何获取 pop() 函数的单个值?
为了获取 pop() 函数的单个值,我尝试了以下方法:
val L=[1,2,3];
val c=pop(L);
val it = SOME (1,[2,3]) : (int * int list) option // is this like a couple?
val c1=#1(c);
但是我收到了这个错误:
operator domain: {1:'Y; 'Z}
operand: (int * int list) option
in expression:
(fn {1=1,...} => 1) c```
重新编写你的代码,使其更加惯用:
exception EmptyList;
fun myPop([]) = raise EmptyList
| myPop(x::xs) = SOME (x, xs);
列表不是可变类型。您从
option
函数获得的 myPop
类型值也不是。
如果您想在调用
myPop
后对列表的剩余部分进行操作,则需要显式地将 that 列表传递给函数调用。调用 myPop
后,原始列表具有相同的值。
使用
myPop
来实现iter
,例如:
fun iter f lst =
let
val SOME (x, xs) = myPop(lst)
in
f(x);
iter f xs
end
handle EmptyList => ();
当然,我们真的只是写:
fun iter _ [] = ()
| iter f (x::xs) = ( f(x); iter f xs );