|
 |
Darren New wrote:
> Assume Haskell doesn't have the "0xABC" kind of syntax for hex literals.
> Could you add that with Haskell, or TH?
You could write a function that converts an ASCII hex string into a
number, and then pass the string to that. So you end up saying
if x == hex "0xABC" then...
or similar.
If you use TH instead, you can write a "splice":
if x == $(hex "0xABC") then ...
This is more typing, but the conversion to hex now happens at
compile-time, not runtime. (It's plausible that calling a function with
a constant will get executed at compile-time anyway, but not guaranteed.
TH guarantees it. And if it errors, it errors at compile-time.)
Alternatively you can use the new "quasi-quoting" feature:
if x == [$hex| 0xABC] then ...
Notice the lack of quote marks. Quasi-quoting is really intended for
where you want to write a big long data literal, but it's too wordy. For
example, rather than writing
x = Expr_Define (Expr_Function (Name_Literal "Sinc") [Expr_Var
(Name_Literal "x")]) (Expr_BinOp BinOp_Divide (Expr_Function
(Name_Literal "Sin") [Expr_Var (Name_Literal "x")]) (Expr_Var
(Name_Literal "x")))
(assuming I even nested all those brackets right!), you write an
expression parser, and then do
x = [$parser| Sinc(x) = Sin(x) / x]
and it generates the same thing, at compile-time. As well as generating
expressions, you can also use it to generate patterns for pattern
matching. (Your parser of course has to distinguish between expression
variables and Haskell variables somehow...)
However, there is no way in Haskell to make it so that some arbitrary
new string can be used as a literal, anywhere in the program. You have
to tell the compiler what function to use to parse this stuff, one way
or another.
--
http://blog.orphi.me.uk/
http://www.zazzle.com/MathematicalOrchid*
Post a reply to this message
|
 |