0

Context:

I am trying to define a function in that inserts 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 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]
Community
  • 1
  • 1
T.Woody
  • 1,142
  • 2
  • 11
  • 25

1 Answers1

1

It is impossible. OCaml's list is immutable, you can't change it. You can't change its values, you can't change its length.

ivg
  • 34,431
  • 2
  • 35
  • 63
  • Thanks! I find this slightly odd, as my previous experience comes from always being able to alter the form of a list. That being said, the best way to go about this would to do a `let nList = insertion SOME_VAL SOME_LIST`? If so, do you mind if this is added to your answer? – T.Woody Oct 04 '14 at 23:15
  • 1
    OCaml is functional programming language. So by default most data structures a immutable (or persistant, as we say). Also, please note, that an expression `let var = expr` doesn't actually change a value of `var` to `expr`, its just create a new binding, i.e., binds a name `var` to a some object `expr`. If it is just happend, that in a current scope such name already exists, then it is just shadowed (cf, python's maps). That's why we a trying not to use term 'variable' since it can be confusing to a newcomers. We use names and values. Hope, this helps! – ivg Oct 04 '14 at 23:23
  • Thanks, again! I wanted to clarify this point, as well, since the snippet of code in my previous comment was a resolution that I was looking for (but reluctant to use >,<). Again, thank you for your time! – T.Woody Oct 04 '14 at 23:26