0

I am writing a recursive function move that takes two lists and inserts the elements from the first list to the second list in reverse order..

we have a predefined list datatype

type ilist = E | L of int * ilist

For example:

move L(2, L(3, E)) L(1, L(2, E)) 

would give me

L(3, L(2, L(1, L(2))))

I think i am having syntax errors with my code. Also not sure if i can prepend using cons since it is a pre-defined list datatype. Any help is appreciated!

let rec move l r =
match l with
 | E -> []
 | L(h,E) -> h::r
 | L(h,t) -> move t r

1 Answer 1

3

There are a couple of syntactic errors and type checking errors in your function. You need to indent things properly and parenthesize the arguments of your sample call. Since you want to return the existing list, which is of type ilist, you also need to replace [] and :: in your right hand side implementation with your constructors L and E. Fixing the issues gives:

let rec move l r =
  match l with
  | E -> E
  | L(h,E) -> L(h, r)
  | L(h,t) -> move t r

move (L(2, L(3, E))) (L(1, L(2, E)))

This runs, but it does not quite do the right thing. To actually get this to do what you want, you need to:

  • In the first case, if you call move E (L(1, E)) you should get back L(1, E) but your implementation just returns E. You need to return r.
  • In the last case, you are not using h so it will get dropped. You need to append this to the r value or the result of the recursive call using the L constructor.
  • You also do not need the second case - if you get things right, the first and the last cases will cover all options you need.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.