I need a tail recursive function that appends a list1 infront of list2.
I tried it this way
let rec append lst1 lst2 acc =
match lst1 with
| [] -> acc @ lst2
| hd::tl -> append lst1 tl (hd::acc);;
append [1;3;4] [3;4;2] [];;
But the result is "time out" every time
You have unbounded recursion because you're not updating
lst1when you evaluate your test case:This will run forever, which explains your "time out" issue.
You need to update
lst1. E.g.But that's not right. You need to think about your logic. Lists in OCaml are singly-linked lists.
[1; 3; 4]is equivalent to1 :: 3 :: 4 :: []and[1; 3; 4; 3; 4; 2]is1 :: 3 :: 4 :: 3 :: 4 :: 2 :: [].You just need to replace
[]in the first list with[3; 4; 2]. The basic form for this is going to look like: