我需要有关F#字符串连接的帮助。
给定一个整数n和列表l,我必须删除l中所有出现的n。例如:
remove 1 (L(1, L(2, L(3, E)))) should give me L(2, L(3, E))
我的代码:
type ilist = E | L of int * ilist
let rec remove n l =
match l with
| E -> []
| L(h,E) -> if (h=n) then remove h (L(h,E))
else [h, E]
| L(h,t) -> if (h=n) then remove h t
else [h :: (remove n t)]
我收到一个类型错误,说最后一行应该有int * ilist类型 但这里有类型'列表
任何帮助,将不胜感激!谢谢
主要问题是常见问题。你将结果包装在[]
中,忘记了h :: remove n t
已经是一个列表了。所以我的固定版本:
let rec remove n l =
match l with
| E -> []
| L(h,t) -> if (h = n) then remove n t
else h :: (remove n t)
请注意,你可以摆脱你的中间情况,因为它可以通过匹配t
与E
巧妙地解决。
我也把你的remove h
改成了remove n
;即使它们保证相等,我认为n
是递归函数的“常量”参数更好。