4 ms·
You can perfectly easily write with-foobar functions of any kind, so macros aren't a win there, except maybe in Lisp where it saves you a parenthesis or two. Y
by sarehu 18y ago
You can perfectly easily write with-foobar functions of any kind, so macros aren't a win there, except maybe in Lisp where it saves you a parenthesis or two. You can replice define-memoized-function with
(define f (memoize (lambda args ...)))
so I don't see what macros gain you there. (Well, they save you from having to write lambda.) Especially if you're using a language with 'nicer' syntax, like Haskell:
withFile $ \h -> do
...
fib = memoize $ \n -> if n <= 1
then n
else fib (n - 1) + fib (n - 2)
Example (2) seems interesting though. And I'd like to see some examples of (3) that couldn't be so easily overcome. (Granted, my example is rather fake, since I don't know how you'd implement memoize for general types that only have a comparison function on them, without resorting to using some IO operation.)
- shiro 18y agoYes, with nicer closure syntax and/or lazy evaluation, lots of macro use cases can be eliminated. However, making single definition work as multiple definitions is a pattern that I haven't find ways other than macros. For example, think of defenum macro that expands to a bunch of defconstants: (defenum (ONE 1) TWO THREE FOUR (TEN 10)) => (progn (defconstant ONE 1) (defconstant TWO 2) (defconstant THREE 3) (defconstant FOUR 4) (defconstant TEN 10)) (Haskell programmers would use types for enum-kind of stuff, but suppose that you really need to associate numbers to those symbols.) Or you can go further to name the enum itself, defining conversion functions between symbolic names and their values: (defenum the-numbers ONE TWO THREE ...) => (progn (defun symbol->the-numbers (sym) (case sym ((ONE) 1) ...))) (defun the-numbers->symbol (num) (case sym ((1) 'ONE) ...))) (defconstant ONE 1) ...) Without macros, you need to have some procedural interface to modify the global environment to realize these (which is, imho, worse than macros).
- sarehu 18y agoI wasn't asking why macros were useful in general, but thanks anyway.