0

I am quite a fan of functional programming, I do know about pattern matching and multiple dispatch, and that's how I found about predicate dispatch and was wondering ever since whenever or not it has something to do with pattern matching.

I did read this SO thread: What is Predicate Dispatch but still couldn't get my answer regarding the relation between pattern matching and predicate dispatch. I believe that pattern matching and predicate dispatch are indeed similar, if not equivalent, but would like to hear a few opinions.

Consider this Elixir code:

def function(%{a_flag: True}=struct) do
    # do smth
end

def function(struct) when is_nil(struct.field) do
    # do smth else
end

def function(struct) do
    # default case
end

It does look like the function is picked at runtime based on the properties of the input argument(s), which is exactly what predicate dispatch is. The when part looks similar to how predicate dispatch is proposed in this article: http://web.cs.ucla.edu/~todd/research/oopsla04.pdf

Please share your knowledge/opinion on this matter.

2 Answers2

0

I hadn't heard of "predicate dispatch", but I can share with you some insights on how Elixir handles pattern matching in function clauses.

Pattern matching in Elixir functions works a bit like routing in web applications: functions are tried in the order listed until a match can be made, and then that function is executed. This means that the most specific matches should be listed first, and the least-specific (or catch-alls) should be listed last. In fact, you will see warnings if you are using an appropriate linter/language-server if you have constructed functions in a way that one cannot be reached.

For example, these definitions are problematic:

def something(_) do
   # This would always match 
end

def something(%{foo: nil}) do
   # so this can never match; the previous function def is too broad
end

We can rewrite your example a bit to use only pattern matching (instead of using pattern matching and guards):

def function(%{x: true} = struct) do
    # do something when x == true
end

def function(%{y: nil}) do
    # do something else when x != true AND y == nil
end

def function(struct) do
    # default case
end

The compiler literally turns all of this into a series of conditionals, but the function clauses offer a nice expressive syntax.

Everett
  • 8,746
  • 5
  • 35
  • 49
  • Thank you @Everett, even if I wasn't looking for an explanation of how pattern matching works but rather if it's equivalent to the concept of predicate dispatch. – Alexandru Burlacu Mar 30 '21 at 08:32
0

From my limited understanding, it seems predicate dispatch happens at function call level, while pattern matching is just syntactic sugar for if/else and object destructuring.

So, even if they seem related, predicate dispatch is different from pattern matching.