'Pattern Matching a 2d array with tuples

I have a 2d list that looks as follows (string * int) list list

[ [("size1", 1);("size2",2)] ; [("size3",3);("size4",4)] ]

When given a string name, I want to return the int associated with that name

"size1" -> 1
"size2" -> 2
"size4" -> 4

I have an idea of how I would do this using the List module but how would I do something like this using pattern matching?



Solution 1:[1]

An OCaml pattern essentially matches a single constructor of a type, with subpatterns in the places of the constructed values. For a list, this means you need to pick the number of :: constructors you want to have in your pattern. Hence there's no OCaml pattern that matches at an arbitrary place in a list. So there's no way to solve your problem with just pattern matching (if I understand what you're trying to do).

If you know the maximum length of your lists you can enumerate all possible lengths, but somehow I doubt this is what you want to do.

My way of looking at it is that OCaml patterns have a very clean and disciplined structure, which allows them to be implemented very efficiently. Other languages (like perl say) have very powerful patterns that can't really be implemented efficiently. They can require more or less arbritrary amounts of retrying of different subpatterns. Naturally being an OCaml guy I much prefer the OCaml approach.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chris