Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SML在列表中添加两对数字_Sml_Smlnj - Fatal编程技术网

SML在列表中添加两对数字

SML在列表中添加两对数字,sml,smlnj,Sml,Smlnj,我试图获取一个列表,例如[1,2,3,4],然后将列表中的每一对数据相加,得到一个新的列表[3,7]。我不断地犯错误,我不知道这意味着什么。任何帮助都将不胜感激 fun listsum x = if null x then 0 else hd x + hd(tl x) :: listsum(tl x) + listsum(tl(tl x)); stdIn:3.6-3.58错误:运算符和操作数不一致[重载] operator domain: 'Z * 'Z list operand:

我试图获取一个列表,例如[1,2,3,4],然后将列表中的每一对数据相加,得到一个新的列表[3,7]。我不断地犯错误,我不知道这意味着什么。任何帮助都将不胜感激

fun listsum x =
if null x then 0
else hd x + hd(tl x) :: listsum(tl x) + listsum(tl(tl x));
stdIn:3.6-3.58错误:运算符和操作数不一致[重载]

 operator domain: 'Z * 'Z list
  operand:         'Z * 'Y
  in expression:
    hd x + hd (tl x) :: listsum (tl x) + listsum (tl (tl <exp>))
运算符域:“Z*”Z列表
操作数:“Z*”Y
在表达上:
hdx+hd(tlx)::listsum(tlx)+listsum(tl(tl))

这里有两个问题:第一个问题是在最后一行中,您要求两个列表的总和
+
;第二个是在
if
的一个分支中返回
int
,在另一个分支中返回
列表

第一个问题看起来就像一个thinko:您已经在
的左侧完成了所有需要的添加,剩下的就是在列表的其余部分递归

两个都修好了,

fun listsum x =
    if null x then []
    else hd x + hd (tl x) :: listsum (tl (tl x));

下面是一个递归函数,该函数的模式与列表中的模式匹配
listsum
在奇数长度列表上引发异常,该列表将忽略最后一个奇数值

fun sumTwo(xs: (int) list) =
 case xs of
   h :: ht :: t  => h + ht :: sumTwo(t)
   | h :: []  => []
   | [] =>  []
测试:

- sumTwo [1,2,3];
val it = [3] : int list
- sumTwo [1,2,3,4];
val it = [3,7] : int list

这是有道理的,我看到我试图添加两个递归语句,而我的数学已经完成,只需要一个递归语句。因此出现了过载错误。谢谢你回答我的问题。