简体   繁体   中英

Ocaml: Recursion: intersection

function name: intersection: takes 2 lists and returns list of all elements that appear in both

ie: [1; 2; 2; 3; 4; 4; 3] [2; 3] -> [2; 2; 3; 3]

let rec intersection (l1: int list) (l2: int list) : int list = 
    begin match l1, l2 with
      | hd :: tl, hd2 :: tl2 -> if hd = hd2 then hd :: intersection tl l2
                                            else intersection tl l2
      | _ -> []
    end

There is a problem with this code, but I'm not sure how to fix it - The code will run through and get [2; 2] because it keeps comparing to 2, the first element in l2, but I want l1 to also compare with tl2, does anyone have any suggestions?

 Should I add another match [], [] -> to clarify base case at the beginning?

how do you refer to the first element in the other list?

Use another match statement:

let rec intersection (l1: int list) (l2: int list) : int list = 
    begin match l2 with
      | []         -> []
      | hd2 :: tl2 -> begin match l1 with
                        | []         -> …
                        | hd1 :: tl1 -> …
                      end
    end

You can also simplify this by omitting the begin / end parenthesis that are unnecessary in this case, and by matching upon a tuple right away:

let rec intersection (l1: int list) (l2: int list) : int list = match l1, l2 with
  | [],       _        -> []
  | hd1::tl1, []       -> …
  | hd1::tl1, hd2::tl2 -> …

(Disclaimer: I ignored the question whether looking at the two first elements in the same function is useful for implementing intersection at all)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM