3 ms·
Again, you don't want to change regex, you want to create it in the first place. Maybe a simpler example, what if I wanted this in (pseudo-)C? with(s = fo
by reikonomusha 4y ago
Again, you don't want to change regex, you want to create it in the first place.
Maybe a simpler example, what if I wanted this in (pseudo-)C?
with(s = fopen("/foo/bar", ...)) {
...;
...;
println(readln(s));
...;
...;
}
When the "with" clause ends, the file will automatically be closed. This is more or less bog standard RAII expressed as a new language construct.
In Lisp, this is a feature you could build and provide as a library feature. In fact, we can do it, straight here in an HN comment.
(defgeneric destroy (x)
(:documentation "A destructor for use with the WITH feature".))
(defmacro with ((var = val) &body body)
"Python-style RAII macro. VAR will be
bound to the value of VAL, and upon
exiting scope, will be destroyed with
DESTROY."
(assert (eq = ':=))
(let ((orig (gensym)))
`(let* ((,orig ,val)
(,var ,orig))
(unwind-protect
(progn ,@body)
(destroy ,orig))))
We can register a new destructor easily for open file streams:
(defmethod destroy ((s stream))
(close stream))
(We could add some more error handling, etc. to make it more robust.)
Now, we effectively have RAII in Lisp:
(with (s := (open "/foo/bar" ...))
...
...
(write-line (read-line s))
...
...)
This is now real Lisp code you can actually run, completely integrated into the language, and nicely orthogonal to the existing gamut of features.
This is a concept we can use almost immediately after learning about it, instead of waiting for Python's PEP 6363 to pass with consensus from people who may have different programming goals than you do.
- michaelwww 4y agoI can see a lot of uses for macros, but in this case C# has a "using" keyword and the designers have put a lot of thought into it and how it is called in a wide variety of situations. Lisp was a language developed in a world when people worked on their own cars, like me. I would have loved Lisp if I had found it earlier, like about the time I rebuilt my VW engine in the 80's.
- deleted 4y ago[deleted]
- pjmlp 4y agoMany of the language simplifications on more recent C# versions, code generators, Rosylin analysers, expression trees are all features that in Lisp boil down to one thing, macros.
- deleted 4y ago[deleted]