简体   繁体   中英

Ocaml Recursion

Intersection [1;2;2;3;4;4;3][2;3] = [2;2;3;3]

There is something wrong with my code because it currently returns [2;2] since it won't match with t2, only h2, does anyone have any suggestions on the direction I should be thinking in to change this?

let rec intersection (l1: int list) (l2: int list) : int list =
  begin match l1, l2 with
    | h1::t1, h2::t2 -> if h1=h2 then h1::intersection t1 l2 
                                 else intersection t1 l2
    | _ -> []
  end

Note that both of your recursive calls pass l2, the entire second list. This means that h2 is always going to refer to the same element, the first element of the second list. This explains why you're only getting matches on 2 in your example.

You need to look deeper into the second list.

As a side comment, this function isn't easily represented as a single recursive function IMHO. It might be better to think of having two separate sub-operations. In particular, you're interested in whether an int appears in l2 and this is its own separate question.

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