[MLton] using fold to write numeric constants
Vesa Karvonen
vesa.karvonen@cs.helsinki.fi
Fri, 10 Feb 2006 18:24:09 +0200
Quoting Stephen Weeks <sweeks@sweeks.com>:
> The following code shows how to use fold to conveniently write numeric
> constants in any base of various types. For example,
>
> N i 10 `1`2`3 $
>
> denotes 123:int in base 10, while
>
> N ii 8 `2`3 $
>
> denotes 19:IntInf.int in base 8.
Neat!
(((Here is how one can do similar things with the C99 preprocessor:
http://cvs.sourceforge.net/viewcvs.py/chaos-pp/order-pp/example/binary.h?view=markup
Warning: Not to be taken too seriously!)))
Looking briefly at the code, I noticed a minor simplification:
> fun make (zero, op *, op +, op <, op <=, i2x, x2s) base =
^^^^ ^^^^^
Only one of those is needed. For example, using only `op <' you could write
if not (i < zero) andalso i < base then
instead of
> if zero <= i andalso i < base then
This would be a useful simplification (from the user's point-of-view) if the
`make' function would not be local.
The `zero' could also be eliminated easily. Instead of passing 0 to `make',
you can compute a zero using the expression `i2x 0'. Of course, you could
also implement `op *' in terms of `op +' and `op <', but that is likely to
be inefficient (or maybe I'm underestimating MLton ;-)).
(These issues are fresh on my mind, because I've been thinking about using
higher-order functions, like `make', to implement a benchmark
http://shootout.alioth.debian.org/gp4/benchmark.php?test=recursive&lang=all
for MLton.)
-Vesa Karvonen