santinic / pampy

Pampy: The Pattern Matching for Python you always dreamed of.
MIT License
3.52k stars 125 forks source link

Return function without call #28

Open fliepeltje opened 5 years ago

fliepeltje commented 5 years ago

The current behavior is that if an action is a function it by default gets called; I have some scenarios where this is undesireable. For instance, I might want to decide how to process data based on an enum and bind my processing function to that enum. I would want to know which function to use, but not yet call it and certainly not with the enum value. Or alternatively I might want to interpret and pattern match on dataset A and based on that determine how to process an entirely different dataset B. Example:

fn = match(exp,
{"field": "some_value"}, fn_a,
{"field": "some_other_value"}, fn_b,
)
fn("some_string")

The above would fail because it would call the function with a dict while the functions expects a string.

currently the above is possible with the following hack:

fn = match(exp,
{"field" : "some_value"}, lambda x: fn_a,
{"field" : "some_other_value"}, lambda x: fn_b
)

however, this drastically diminishes readability.

I propose one of the following 2 solutions:

  1. Check whether the action is a lambda function and only call it if this is the case
  2. Add a named parameter to match that determines whether the given action is called or not.
adamlwgriffiths commented 3 years ago

Sounds like the better option here is to make a new version of match that suits your needs. Take every second parameter and wrap it in a lambda and then pass that to match.