Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"unfold" for common lisp?

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???

like image 999
nullpointer Avatar asked Oct 26 '09 05:10

nullpointer


People also ask

Is Common Lisp better than scheme?

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.

What is member in Lisp?

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.


2 Answers

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

like image 131
huaiyuan Avatar answered Oct 19 '22 02:10

huaiyuan


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.

like image 22
David Seiler Avatar answered Oct 19 '22 02:10

David Seiler