Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/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
List F#:递归函数:测试元素是否是给定列表的成员_List_Recursion_F#_Boolean - Fatal编程技术网

List F#:递归函数:测试元素是否是给定列表的成员

List F#:递归函数:测试元素是否是给定列表的成员,list,recursion,f#,boolean,List,Recursion,F#,Boolean,我想知道如何编写代码 在F#中实现一个函数,测试一个元素是否是给定列表的成员。这是我想要的型号 val memberof:'a*'a list->bool when'a:equality 下面是正在运行的函数的示例 成员1[1;2;3];; 错误FS0003:此值不是函数,无法应用 (1[1;2;3]);; val it:bool=true (1,[])的成员;; val-it:bool=false (1[2;3;4]);; val-it:bool=false 这就是我所说的 让rec memb

我想知道如何编写代码

在F#中实现一个函数,测试一个元素是否是给定列表的成员。这是我想要的型号

val memberof:'a*'a list->bool when'a:equality

下面是正在运行的函数的示例

成员1[1;2;3];; 错误FS0003:此值不是函数,无法应用

(1[1;2;3]);; val it:bool=true

(1,[])的成员;; val-it:bool=false

(1[2;3;4]);; val-it:bool=false

这就是我所说的

让rec memberof l=
匹配(l:浮动)与
|a.项目(l)->l->bool+(l成员)

让rec memberof l=
将(l:浮动列表)与
|[]->false
|(a:浮动)::b->(a)=(b的成员)->bool

测试用例

let test001 = memberof [1.0; 2.0; 3.0] 0.0    
printfn "test001: %A" test001   

let test002 = memberof [1.0; 2.0; 3.0] 1.0  
printfn "test002: %A" test002   

let test003 = memberof [1.0; 2.0; 3.0] 2.0  
printfn "test003: %A" test003 

let test004 = memberof [1.0; 2.0; 3.0] 3.0  
printfn "test004: %A" test004   

let test005 = memberof [] 0.0    
printfn "test005: %A" test005 
哪个输出

val test001 : bool = false
val test002 : bool = true
val test003 : bool = true
val test004 : bool = true
val test005 : bool = false
问题在于

let rec memberof l =
    match (l:float list) with
    | [] -> false
    | (a:float)::b -> (a)=(memberof b)->bool
是吗

| (a:float)::b -> (a)=(memberof b)->bool
是否正确地使用

 (a:float)::b
然而

 (a)=(memberof b)->bool
这是不对的

对于列表上的递归函数,您希望去掉列表的头部并处理头部。然后您需要再次调用该函数,这次将列表的尾部作为新的列表变量传递,例如

memberof tl item
由于这是一个错误,我们只需要在达到所需的正确或错误时停止。在本例中,当找到true时,函数可以结束,因此无需为列表的其余部分调用
memberof

你要求的特殊签名

val memberof:item:'a*list:'a list->bool当'a:相等时


这些例子来自哪里?因为您的函数甚至没有正确的签名(我不是指
浮点
'a
)还有:这是一个练习吗?因为如果您查看
列表
模块,您可以找到您要查找的内容
 (a:float)::b
 (a)=(memberof b)->bool
memberof tl item
let rec memberof ((item : 'a), (list : 'a list)) : bool when 'T : equality =
    match list with
    | hd::tl ->
        if hd = item then
            true
        else
            memberof (item, tl)
    | [] -> false