Re:A self-infecting datatype in Lisp
by draven on Tuesday January 24, 2012 @09:43AM
(#3504901)
I'm learning Haskell ATM and it looks similar to lazy lists in WHNF, as at each step you get an element and a "thunk" that can be used to compute the next step.
Re:A self-infecting datatype in Lisp
by eridius on Tuesday January 24, 2012 @03:45PM
(#3506671)
This is similar to one of my favorite Haskell "tricks": Tying the Knot. It's kind of a mindfuck the first time you do it, but it also feels really really cool.
Re:A self-infecting datatype in Lisp
by SeanLuke on Tuesday January 24, 2012 @11:30AM
(#3505426)
Since he mentioned self-infecting Lisp functions (which seems to me to be unrelated to his main topic but whatever), I should mention that I put together a Lisp self-infecting "virus" (so to speak) a long time ago. My original version -- which was beautiful and I have conveniently forgotten -- used a quine to deliver the payload. But here's a version I whipped up for HN a few weeks back which gives you the idea.
;; run this on SBCL
(sb-ext:unlock-package :common-lisp)
(let (syms) (do-symbols (s :common-lisp) (if (fboundp s) (push s syms)))
(labels ((worm (sym)
(let ((next (elt syms (random (length syms))))
(old (symbol-function sym)))
(format t "~%Worm attacks ~a, next target is ~a!~%" sym next)
(setf (symbol-function sym)
(lambda (&rest args)
(when next (worm next) (setf next nil)) (apply old args))))))
(worm '+)))
;; now try adding some numbers (and so on)
The code for the cycle Haskell function is really simple: http://hackage.haskell.org/packages/archive/base/latest/doc/...
http://www.haskell.org/haskellwiki/Tying_the_Knot
My guess: the nested defun is not only defined in the enclosing defun scope as it may seem, but in the whole current package.
http://www.lispworks.com/documentation/HyperSpec/Body/m_defu... "Defines a new function named function-name in the global environment"
Is it only a bad idea because it's bad style or is there more to it?
Then it's just neat.