Matching the Ocaml Pattern

Hey guys, I'm pretty new to OCaml and pattern matching, so it was hard for me to figure it out.

Say I have a list of tuples. What I want to do is map the parameter to one of the tuples based on the first element of the tuple, and in 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 the map_left_to_right "b" list, I want to get 2 in return. Therefore, I want to list all the first elements in the rule list and map the parameter to one of these elements, but I'm not sure how to do this. I thought I needed to use List.iter or List.for_all to do something like this. Any help would be greatly appreciated. Thanks!

+4
source share
2 answers

Pattern matching is for when you want to map 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 specify the default value when the item is not found. Here map_left_to_right "b" list 0 will return 2 as expected, and map_left_to_right "z" list 0 will return 0.

+6
source

Only match matches with fixed patterns, not variables. The corresponding use of correspondence in this case will look like this: (pay attention to the inclusion of "default", 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 it will be called like this:

 map_left_to_right "b" list 0 

All this is functionally equivalent to the code in another answer, and in practice I would recommend using this code, because it is smaller and uses existing libraries better, but I thought I would give this code because it better illustrates how it will be applied in this case matching mapping.

+1
source

Source: https://habr.com/ru/post/1335510/


All Articles