Intersection between two lists F#

五迷三道 提交于 2019-12-23 09:49:04

问题


I am looking for a function that takes the intersection between two lists and creates a new list, I have this function: let intersect x y = Set.intersect (Set.ofList x) (Set.ofList y) that do what I ant but I dont want to use any of the inbuilt functions in F#


回答1:


It is best to use the library stuff, but if you can't

If we assume that the input lists are sorted (use List.sort or write your own) :

let rec intersect a b =
    match a with
    |h::t -> match b with
             |h2::t2 -> 
                 if h=h2 then h::(intersect t t2)
                 else if h>h2 then intersect t b else intersect a t2
             |[] -> []
    |[] -> []



回答2:


I agree that converting lists to sets is not good in this case.

Here is another alternative that works without conversion to sets but uses the inbuilt Enumerable.Intersect function:

open System.Linq

let intersect (xs:'a seq) (ys: 'a seq) = xs.Intersect(ys)

You can call this function with FSharpList.



来源:https://stackoverflow.com/questions/13561301/intersection-between-two-lists-f

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!