简体   繁体   中英

Ocaml list recursion

This is what I have for my code so far:

let equiv=[];;
let unequiv=[];;

let rec isEqual equiv unequiv compareVal x lst =
  match lst with
  |[]->[]
  |a::b-> if x a compareVal=true then (a::isEqual equiv unequiv compareVal x b::equiv) @ (isEqual equiv unequiv (List.hd unequiv) x unequiv)
          else a::isEqual equiv unequiv compareVal x b::unequiv

However when I run it gives me an error: Image

My intended output should look something like this: [[a,v,c],[s,f,t]] Is there a flaw in my logic?

Your code is hard to read, you should decompose it:

From what I understand, if your list is not empty, you check if xa compareVal is true , this can be simplified as if xa compareVal .

In that case you put the head of your list in front of a recursive call where almost everything remains the same except lst that is transformed into b:: equiv and you append this list to a recursive call with compareVal being equal to the head of unequiv and the recursive call being applied to unequiv .

In the other case, you just append the head of your list to a recursive call in which only the checked list is modified.

What can we know from your code?

  • Since you wrote a:: b , a is of type 'a and b of type 'a list
  • You write xa compareVal = true so x is of type 'a -> 'b -> bool and compareVal is of type 'b
  • a:: isEqual... means that isEqual returns an element of type 'a list
  • b:: equiv is used as the lst argument of your function so its type should be the same as a:: b but here is the problem, b is used as a head in b:: equiv so its type is 'a and as the tail in a:: b so its type is 'a list . This type is infinitely recursive and OCaml won't let you do that (for good reasons).

Try to write exactly what you want, to divide it in smaller problems and to write your code accordingly or you'll be lost rapidly.

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