recursion - Appending two lists on Ocaml -


so 1 way append 2 lists:

let rec append l1 l2 =   match l1   | h :: t -> h :: append t l2   | [] -> l2 

but trying write tail-recursive version of append. (solve problem before calling recursive function).

this code far, when try add append in first if statement code becomes faulty weird reasons.

let list1 = [1;2;3;4] let list2 = [5;6;7;8]    let rec append lista listb =   match listb   | h :: taillist -> if taillist != []     begin      lista @ [h];     (* cant put append recursive call here because causes error*)   end else   append lista taillist;  | [] -> lista;;   append list1 list2;; 

any appreciated, thanks.

the easiest way transform non tail-recursive list algorithm tail-recursive one, use accumulator. consider rewriting code using third list, accumulate result. use cons (i.e., ::) prepend new elements third list, have result of concatenation. next, need reverse list.rev et voila.


Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

gradle error "Cannot convert the provided notation to a File or URI" -

ios - Possible to get UIButton sizeThatFits to work? -