Reputation: 151
I am pretty new to OCaml and pattern matching, so I was having a hard time trying to figure this out.
Say that I have a list of tuples. What I want to do is match a parameter with one of the tuples based on the first element in the tuple, and upon doing so, I want to return the second element of the tuple. So for example, I want to do something like this:
let list = [ "a", 1; "b", 2; "c", 3; "d", 4 ] ;;
let map_left_to_right e rules = match e with
| first -> second
| first -> second
| first -> second
If I use map_left_to_right "b" list, I want to get 2 in return. I therefore want to list out all first elements in the list of rules and match the parameter with one of these elements, but I am not sure how to do so. I was thinking that I need to use either List.iter or List.for_all to do something like this. Any help would be appreciated. Thanks!
Upvotes: 4
Views: 2263
Reputation: 5668
Match only matches against fixed patterns, not variables. An appropriate use of matching in this case would look like this: (note the inclusion of a "default" just as in the other answer)
let list = [ "a", 1; "b", 2; "c", 3; "d", 4 ]
let rec map_left_to_right e rules default = match rules with
[] -> default (* No rules left to match *)
| (first,second)::rest -> (* At least one rule remaining, which we'll put into first,second *)
if first = e
then second
else map_left_to_right e rest default
If we want to return 0 if nothing is found, then this would be called like so:
map_left_to_right "b" list 0
All of this is functionally equivalent to the code in the other answer, and in practice I would recommend using that code since it's smaller and makes better use of existing libraries, but I thought that I would give this code because it better illustrates how pattern matching would actually be applied in this case.
Upvotes: 1
Reputation: 24577
Pattern matching is intended for cases where you want to match a fixed list of patterns. In your current situation, the idiomatic thing to use is List.assoc
:
let map_left_to_right e rules default =
try List.assoc e rules with Not_found -> default
You need to provide a default when the element is not found. Here, map_left_to_right "b" list 0
would return 2 as expected, and map_left_to_right "z" list 0
would return 0.
Upvotes: 6