我正尝试写产生含而不元素x的给定列表的新列表的功能。
莫斯科ML说,某些情况下是在这场比赛中使用。
fun delete (x,list) = delete(x,[])
|delete(x,(first::rest)) = if first = x then delete(x,rest) else first::delete(x,rest)
我正尝试写产生含而不元素x的给定列表的新列表的功能。
莫斯科ML说,某些情况下是在这场比赛中使用。
fun delete (x,list) = delete(x,[])
|delete(x,(first::rest)) = if first = x then delete(x,rest) else first::delete(x,rest)
以下是我会做它在标准ML ::
fun delete (item, list) =
case list of
[]=>[]
| xs::ys => if item = xs then delete(item,ys)
else xs::delete(item,ys)
不使用的情况下:
fun delete (item, list) = List.filter(fn x => x <> item) list
没关系的polyequal迹象。
当对一个呼叫delete
被执行,定义函数的模式是(基本上)试图顺序。 由于第一图案中的每个列表已经匹配,第二图案永远不会达到。 这就是为什么编译器会抱怨。
换句话说,你要么必须重新排序的情况下,或更好的,让他们不相交(例如,通过更换list
与[]
在第一种情况下)。
额外提示:第一种情况的右侧也似乎是错误的。 这将始终进入无限循环。
That's because your first case matches any list, so the second case will never be used.
Remember that the case are tried in the order they're written, not selected based on which is the "best" match.
You also have a slight problem of infinite recursion with
delete (x,list) = delete(x,[])
Since list
will match []
, it will just recurse forever.
If you delete something from an empty list, the result should be the empty list.
You can do one of two things.
Either move the non-empty case first:
fun delete (x, y:ys) = if y = x then delete(x, ys) else y::delete(x, ys)
| delete (x, list) = []
Or, more common, make the first case only match the empty list:
fun delete (x, []) = []
| delete (x, y:ys) = if y = x then delete(x, ys) else y::delete(x, ys)