从列表中删除f#

Pod*_*odo 1 recursion f# list

我今天晚上一直在使用f#中的列表(创建,添加,搜索等),并且最近卡在列表项删除上.代码很简单.

let menu = [("pizza",17);("hotdog",5);("burger", 12);("drink",3);
("milkshake",4)]

//If key is in dictionary , return new dictionary with value removed
//otherwise return dictionary unchanged
let rec remove dict key =
    match dict with
    //if the list is empty, return an empty list
    | [] -> []
    //if the list is not empty and the head meets the removing criteria
    //return a list obtained by reiterating the algorithm on the tail
    //of the list
    | (k,v) :: tl when k = key -> tl :: remove tl key
    //if the list is not empty and the head does not meet the removing criteria
    //return a list obtained by appending the head to a list obtained by
    //reiterating algorithm on tail of the list 
    | (k,v) :: tl -> (k,v) :: remove tl key
Run Code Online (Sandbox Code Playgroud)

错误来自函数的最后一行,| (k,v) :: tl -> (k,v) :: remove tl key.显然,它不承认(k,v)列表的头部,而只是看到一个带有值的元组.这是有道理的,我不知道我还能期待什么,但问题是我不知道如何解决它.我尝试将元组放在列表中,[(k,v)]但这会让事情变得更糟.我甚至试过,| hd :: tl -> hd :: remove tl key但我有完全相同的问题.我写的每个其他函数都接受了hd和tl作为模式匹配中的列表.

我该如何解决这个问题?

Gus*_*Gus 5

第二名后卫是错的.您正在使用尾部两次,并且因为您在cons操作中将它用作第一个参数,所以它不会键入check(它需要单个元素,而不是列表).

将其更改为:

| (k,v) :: tl when k = key -> remove tl key
Run Code Online (Sandbox Code Playgroud)