How to update a value in ref list of (string*int)

Hi,

I have ref list l:((string * int) list ref-

let l = ref [(“a”,1);(“b”,0)];;

Now I want to update the value of b to 1. how can I do that?

OCaml lists are immutable, and variables like l can’t be changed to refer to a new value. So the right way to think about this is to ask how to create a new list with the desired value.

Your list has the structure of an “association list” with strings as the keys and ints as the values. So you can create a new list like this:

let l2 = ("b", 1) :: List.remove_assoc "b" l

This new list has the entry for "b" at the beginning. In general, association lists are intended to model sets, so the order is not considered to be relevant.

If you care about the order of the resulting list, you will probably have to write your own function to create the new list.

2 Likes

I am sorry for confusion. Lets say I have ref list.

Lists are still immutable, so this doesn’t change much.

If you have

let l = ref [("a",1); ("b",0)]

Then you can update the referenced value like this:

l := ("b", 1) :: List.remove_assoc "b" !l

Then I should use arrays for this purpose?

If you need a mutable and associative container, check Hashtbl

1 Like

It depends what you’re trying to achieve. As @Juloo says, a hash table would be a good solution for real code. If you’re just trying to learn about OCaml (which is what I assumed), you might instead want to think about how to achieve your desired computation using immutable values. An association list is a quick and dirty solution for small amounts of data. You can use a Map as an immutable association that can handle larger amounts of data.

Arrays are mutable, but they are of fixed length. If you have a set of associations that grows and shrinks, arrays aren’t going to be convenient either.

If you just want to get something working I’d follow @Juloo’s suggestion.