F#: Filter items found in one list from another list

后端 未结 3 626
野趣味
野趣味 2021-01-20 06:57

Say I have two lists:

let a = [1 .. 1000]
let b = [250 .. 500]

How do I get a new list that contains the values {1-249, 501-1000}?

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-20 07:14

    Since your list is sorted, you can solve this in linear time using this (non-tail recursive) function:

    let rec except a b =
        match (a, b) with
        | [], x | x, [] -> x
        | x::xs, y::ys ->
            if x < y then x :: except xs (y::ys)
            elif x > y then y :: except (x::xs) ys
            else except xs ys
    

    Tail-recursive version:

    let rec except_tail_recursive a b =
        let rec loop acc a b =
            match (a, b) with
            | [], x | x, [] -> (List.rev acc) @ x
            | x::xs, y::ys ->
                if x < y then loop (x::acc) xs (y::ys)
                elif x > y then loop (y::acc) (x::xs) ys
                else loop acc xs ys
        loop [] a b
    

提交回复
热议问题