Ocaml Pattern Matching

advertisements

Hey guys, I'm 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!


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.