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???
Common Lisp is a large language compared to Scheme, and that is good. Many things in Common Lisp that are missing in Scheme, are features that are frequently needed by many programmers. Having these features standardized is a good thing, as opposed to having to add them, often in an ad-hoc way, for each application.
MEMBER function searches a list for the first occurrence of an element (item) satisfying the test. Return value is tail of the list starting from found element or NIL when item is not found. See also MEMBER-IF, POSITION, POSITION-IF, FIND and FIND-IF.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With