This is not a homework question, rather an exam study guide question. What is the difference between pattern matching in Prolog Vs Haskell?
I've done some research and reading up on the theories behind them doesn't really give me a solid understanding between the two. I read that in Prolog, pattern matching is different because it has the ability to unify variables and thus be able to deduce through resolution and spit out the possible answer
eg ?- [a,b] = [a,X]
X = b
Now I'm not sure how to display pattern matching in Haskell. I know that the same query above shown in Prolog will not work in Haskell because Haskell cannot unify like Prolog. I remember somewhere that to get the same answer in Haskell, you have to explicitly tell it through guards.
I know that I am pretty close to understanding it, but I need someone to break it down Barney style for me so I can FULLY understand it and explain it to a 12 year old. This has been bugging me for quite some time and I can't seem to find a solid explanation.
By the way the example shown above was just to display to you guys what I've learned so far and that I'm actually trying to find an answer. My main question does not relate to the examples above but rather a complete understanding on the difference between the two.
Prolog pattern matching is based on unification, specifically the Martelli-Montanari Algorithm (minus the occurs check, by default). This algorithm matches values of the same position, binding variables on one side to a value at corresponding position on the other side. This kind of pattern matching could work both ways, therefore in Prolog you could use arguments as both input and output. A simple example, the length/2
predicate. We could use this to (comment explains the query):
?- length([],0). % is the length of empty list zero?
?- length([a,b,c],X). % what's the length of list consisting of a,b and c?
?- length(L,5). % give me all lists that have length of 5
Haskell pattern matching is a one way matching, to bind variables to different parts of given value. Once bound, it carries out the corresponding action (the right hand side). For example, in a function call, pattern matching may decide which function to call. e.g.:
sum [] = 0
sum (x:xs) = x + sum xs
the first sum binds empty list, while the second binds a list of at least 1 element. Based on this, given sum <a list>
, the result could be either 0
or x + sum xs
depending on whether sum <a list>
matches sum []
or sum (x:xs)
.