简体   繁体   中英

How to solve equal function in ocaml?

Write a function equals: 'a list -> 'a list -> bool equals l1 l2 returns true if the two lists l1 and l2 are equal (ie if they contain the same elements at the same positions), and false otherwise. The constraint is that you cannot use l1 = l2 directly, so you are asked to entirely redefine equality between two lists.

Mine version have errors:

let rec equals l1 l2 =
  match l1, l2 with
    [], [] -> true
  | (_, []) -> false
  | ([], _) -> false
  | (x1::r1), (x2::r2) ->
      if x1 = x2 then equals (x1::r1) (x2::r2) 
      else false;;

(Note: the function must not contain predefined functions )

A recursive function f is guaranteed to terminate if the body of its definition

let rec f x = ... (* ← body *)

only contains recursive calls fy for values of y that are "smaller" than the original argument x of the function (where smaller means x < y for well-founded relation < ).

Once a recursive function compiles without warning about a non-exhaustive pattern matching, the next step should be to check this criteria.

As you asked how to fix your code:

let rec equals l1 l2 =
  match l1, l2 with
    [], [] -> true
  | (_, []) -> false
  | ([], _) -> false
  | (x1::r1), (x2::r2) ->
      if x1 = x2 then equals (x1::r1) (x2::r2) 
      else false;;

should be changed to

let rec equals l1 l2 =
  match l1, l2 with
    [], [] -> true
  | (_, []) -> false
  | ([], _) -> false
  | (x1::r1), (x2::r2) ->
      if x1 = x2 then equals r1 r2 
      else false;;

Why would you pass the whole list x1::r1 again as an argument for equals instead of the rest of the list? Otherwise, your function will never terminate for lists longer than 1, as the size does not get smaller.

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