Context:
I am trying to define a function in ocaml that insert
s an element x
in a list, at either the head
or the tail
of the list, based off of whether the new element is less than the current head
of the list.
The Problem:
The problem is that when I run some code that I created (shown at bottom), my list is going back to its original state and not saving the append that was previously done. I realize that I can just do this with an easy let
statement of a new variable or the same, but I would like to just save the new list as its current form. Can this even be done in ocaml without the creation of a new list?
My question is: How can I append to a list, and save it in its new form, without the creating of a new list or variable.
Research:
I was looking at this answer on SO, and have incorporated it in my code already. However, when I run this code:
let rec insertion x y =
match y with
| [] -> x::y
| h::tl -> if h >= x then x::y
else y@[x]
;;
, accompanied by:
let y = [1;2;3];;
insertion 0 y ;;
y ;;
I return:
val y : int list = [1; 2; 3]
- : int list = [0; 1; 2; 3]
- : int list = [1; 2; 3]