首页 文章

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

提问于
浏览
3

我正在试图弄清楚如何编码 .

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

val memberof:'a *'列表 - > bool'a:equality

以下是该功能的实例 .

成员1 [1; 2; 3] ;;错误FS0003:该值不是函数,不能应用memberof(1,[1; 2; 3]);; val it:bool = true memberof(1,[]);; val it:bool = false memberof(1,[2; 3; 4]);; val it:bool = false

继承人我把它放在一起......

let rec memberof l =
    match (l:float) with
    | a.Item(l) -> l -> bool + (memberof l)

要么

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

1 回答

  • 2
    let rec memberof (l : float list) (item : float) : bool =
        match l with
        | hd::tl when hd = item -> true
        | hd::tl -> memberof tl item
        | [] -> false
    

    要么

    let rec memberof (l : float list) (item : float) : bool =
        match l with
        | hd::tl ->
            if hd = item then
                true
            else
                memberof tl item
        | [] -> false
    

    要么

    let rec memberof (l : float list) (item : float) : bool =
         match l with 
         | [] -> false 
         | hd :: tl -> 
             hd = item
             || memberof tl item
    

    测试用例

    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
    

    由于这是predicate,我们只需要在达到所需的真或假时停止 . 在此示例中,当找到true时,函数可以结束,因此不需要为列表的其余部分调用 memberof .

    对于您要求的特定签名

    val memberof:item:'a * list:'列表 - > bool'a:equality

    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
    

相关问题