1

I have a doubt about the pattern matching in SML. In the book "Programming Language Pragmatics (Second edition)" I read that in SML when you use the pattern matching in a function, the same variable can not appear more than once. The explanation is that pattern matching is used to check if the function can be found in a defined pattern, and not to check if variables are in relation to each others. But it has confused me: why something like this could not be implemented? Here is an example:

fun Eq nil = false
| Eq (e) = false
| Eq x::x::resto = true //Error
| Eq x::y::resto = false

This snippet of code check if the first two elements of a list are equal. So, why the third line of the code is wrong? Thank you.

1

1 Answer 1

2

Pattern matching only compares compile-time constants and does simple variable assignment otherwise. You can't do a variable comparison via pattern matching. You need to remove the third line and extend the 4th line to

Eq x::y::resto = x = y

Pattern matching also happens in order. Since Eq e actually matches everything, it should be your final clause.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the answer. instead of Eq e, it should have been Eq [e].

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.