I learned quite a bit of scheme from SICP but am more interested in common lisp now. I know common lisp's fold
is reduce
, with special arguments for left or right folding, but what is the equivalent of unfold
? Googling has not helped much. In fact I get the impression there is no unfold???
views:
284answers:
2
+3
A:
The common lisp hyperspec doesn't define an unfold
function, but you can certainly write your own. Its scheme definition translates almost symbol for symbol.
David Seiler
2009-10-26 05:47:21
Thanks. That's unfortunate, but I suppose yes I'll write my own. I really like scheme for being so pure and having such beautiful functional goodness, but I've sort of resigned myself to learning the tangled, yet expressive common lisp. It's sort of like learning english rather than esperanto, you know?
nullpointer
2009-10-26 05:55:29
+8
A:
Common Lisp has (loop ... collect ...)
. Compare
(loop for x from 1 to 10 collect (* x x))
with its equivalence using unfold
:
(unfold (lambda (x) (> x 10)) (lambda (x) (* x x)) (lambda (x) (+ x 1)) 1)
In general, (unfold p f g seed)
is basically
(loop for x = seed then (g x) until (p x) collect (f x))
Edit: fix typo
huaiyuan
2009-10-26 12:23:50
Hmm that's interesting. I've been playing around with loop for the past hour :P its great stuff! I love when programming languages have these little sort of embedded sublanguages which have their own syntax and set of rules to understand, like format strings. Loop is powerful stuff!
nullpointer
2009-10-26 20:47:14