Strange tilde syntax

Writing

x = 5

creates a global variable named x, bound to the value 5. Adding a tilde makes the pattern match irrefutable, but it was already irrefutable, so that doesn't make much sense. But it's legal to write something like

(xs, ys) = span odd [1..10]

This defines two global variables, xs and ys, containing all the odd numbers and all the even numbers between 1 and 10. You could even make this irrefutable if you want by adding a tilde. Of course, this pattern can't fail (if the expression is well-typed), so there's no point to that. But consider:

~(x:xs) = filter odd [1..10]

This defines two global variables, x and xs, if the filter returns at least one result. If the filter were to return zero results, the pattern match would fail. (In practice, this means that accessing x or xs would throw a pattern match failure exception.)

You can even write utterly bizarre stuff like

False = True

This seemingly nonsensical declaration pattern-matches the pattern False against the value True, and does nothing either way. It's one of those obscure corners of the language.


The tilde is doing exactly what it did in your other example: it makes the pattern irrefutable (so the pattern match can not fail). The pattern already was irrefutable, of course, in both cases (being a plain variable, which always matches), but that doesn't make the tilde illegal, just unnecessary.

Tags:

Haskell