从F#中删除列表

问题描述 投票:2回答:1

我需要有关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类型 但这里有类型'列表

任何帮助,将不胜感激!谢谢

recursion f# functional-programming pattern-matching
1个回答
3
投票

主要问题是常见问题。你将结果包装在[]中,忘记了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)

请注意,你可以摆脱你的中间情况,因为它可以通过匹配tE巧妙地解决。

我也把你的remove h改成了remove n;即使它们保证相等,我认为n是递归函数的“常量”参数更好。

© www.soinside.com 2019 - 2024. All rights reserved.