Change output direction

Hi, i have this function that delete some elements of a list that are not satisfying certain conditions
let rec get_younger y x= match y with
|[]-> []
|{age=m;name=z;fonction=n}::t-> if (x=m) then {age=m;name=z;fonction=n}::get_younger t x else get_younger t x

My goal is that the function returns the same list but after the modification
in the function above, its create a new list and i don’t want that. I want return the same list but only after modification.

thank you

You can’t do that : in OCaml lists are immutable. And you can write your function :

let get_younger y x = List.filter (fun {age} -> age = x) y

i heard about somthing that callled mutable or ref

Refs can change a value held in a variable, but they can’t change the structure of a list for example they can’t delete elements from a list. Sounds like you really want to use a vector data type. A vector is basically an array which automatically manages changing its own size for you. E.g. you can use , it has a function Vector.remove_if which sounds like exactly what you need.

One more thing I’d add is that if you’re mutating the input vector, get_younger is no longer an appropriate name for the operation, I would recommend changing it to something that makes the mutation more obvious, e.g. keep_younger or even remove_older.

1 Like