user1888863
user1888863

Reputation: 389

Dynamically Generating a function with pattern matching in Ocaml

I am trying to write a function that dynamically generates another function with dynamically specified patterns to match, and I am very lost on how to get started.

Basically, the top-level function takes in a dictionary, where keys are matched to lists of values, and I want to return a function, that pattern matches those keys to the value.

For example, I would pass in a dictionary like [( "a", [1;2;3]); ("b", [3])] and I would get a function that looks like

function 
| "a" -> [1;2;3] 
| "b" -> [3]

Can anyone point me in a direction on how to get started on this?

Upvotes: 0

Views: 330

Answers (1)

glennsl
glennsl

Reputation: 29106

Sounds like what you want is really just List.assoc with the arguments reversed:

let f list key =
    List.assoc key list

let g =
    f [( "a", [1;2;3]); ("b", [3])]

let a = g "a" (* returns [1;2;3] *)

Btw, what you call a "dictionary" is more specifically called an association list. Hence the name of the function :)

Upvotes: 4

Related Questions