Function for overshadowing

Viewed 60

Is it possible to write a function to overshadow a variable?

For example when we return the tail of a list and bind it to the same name as the input list, we overshadow it:

let list = [1;2;3]

let del_last list = 
  let rec aux lst retlst = 
    match lst with 
    | [] -> [] 
    | [t] -> List.rev retlst
    | h :: t -> aux t (h :: retlst)
  in aux list []

let list = del_last list;;
val list : int list = [1; 2]

Is it possible to do so in one function? So that the function automatically binds the output to the name of the input. In this example that del_last binds the name of the input list to the returned list so that afterwards list is [1;2] without calling the function del_last to list manually.

I tried to bind the name of the list to the output in the call of the recursive help function aux but it does a comparison instead and returns a boolean instead of 'a list:

let del_last list = 
  let rec aux lst retlst = 
    match lst with 
    | [] -> [] 
    | [t] -> List.rev retlst
    | h :: t -> aux t (h :: retlst)
  in list = aux list [];;   
val del_last : 'a list -> bool = <fun>
1 Answers

OCaml uses lexical scoping (like most languages except some Lisp). Consequently, a function cannot modify the environment of its caller. In other words, in the code below

let x = 0 (* or anything really *)
let y = f z

one can assert that the name x still refers to the same value after the call to f for any f.

Related