A friend recently asked me if there was a way to generate syntax in
Haskell. A simple example of the sort of thing he was asking about is:
He wants something sort of like if (condition) then (something)
which should evaluate the condition, and if it's true it yields Just
(something)
and if false it yields Nothing
. Obviously you can't
reuse the keywords if
and then
. (Disregarding certain nonstandard
features of the compiler.)
I said well, it's easy to write
myif c v = if c then Just v else Nothing
but that doesn't get his then
in there beacause you use it like
this:
myif (condition) (something)
So then I said you can write
myif c _ v = if c then Just v else Nothing
and use it like this:
myif (condition) "then" (something)
and it will ignore the "then"
. This is kind of gross. And nothing
stops you from writing myif ... "wombat" ...
instead.
But then I had a brainwave, and said you could do this:
data Then = Then
myif c Then v = if c then Just v else Nothing
Now you use it like this:
myif (condition) Then (something)
the Then
will be type-checked and you will get a reasonably
clear error message if you leave it out or misspell it.
I think I am not the first person to invent this technique and that I have seen it before somewhere.
So my question is, is this technique, of making up a one-element type to use as a pretend keyword, something that is common, well-known, uncommon, rare, or unheard-of? If I did this in my Haskell code, would an experienced Haskeller see it and say “wow, that is bizarre” or “Oh, he's just doing that, sure”.