小编Bob*_*son的帖子

f#列表的交集

let rec mem list x = match list with
                 | [] -> false
                 | head :: tail -> 
                   if x = list.Head 
                   then true
                   else mem list.Tail x 
Run Code Online (Sandbox Code Playgroud)

函数mem接受一个列表和一个var X作为参数,并检查列表是否包含值X,如果是,则返回true,如果是,则返回false.

let rec intersection list1 list2 = match list1 with
               | head :: tail -> match list2 with 
                     | head :: tail -> if mem list2 list1.Head = true 
                     then (*add the value to a list*) else intersection list1.Tail list2
               | [] -> failwith "Second list is empty"
       | [] -> …
Run Code Online (Sandbox Code Playgroud)

f# intersection list

8
推荐指数
2
解决办法
2296
查看次数

F#使用函数从列表中删除重复项

我想创建一个获取列表并返回已删除重复项的列表的函数.

let removedupes list1 =
  let list2 = []
  let rec removeduprec list1 list2 =
    match list1 with
    | [] -> list2
    | head :: tail when mem list2 head = false -> head :: removeduprec tail list2
    | _ -> removeduprec list1.Tail list2
  removeduprec list1 list2
Run Code Online (Sandbox Code Playgroud)

我使用这个"mem"函数进入列表,看看该值是否已经存在,在这种情况下,我想继续递归.

let rec mem list x = 
  match list with
  | [] -> false
  | head :: tail -> 
    if x = head then true else mem tail x 
Run Code Online (Sandbox Code Playgroud)

当我测试这个代码时,我得到了

let list1 = …
Run Code Online (Sandbox Code Playgroud)

f# list

2
推荐指数
3
解决办法
2141
查看次数

标签 统计

f# ×2

list ×2

intersection ×1