Path: ...!eternal-september.org!feeder3.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: "B. Pym" Newsgroups: comp.lang.lisp Subject: .Re: simple lisp function Date: Thu, 6 Jun 2024 10:38:54 -0000 (UTC) Organization: A noiseless patient Spider Lines: 41 Message-ID: MIME-Version: 1.0 Content-Type: text/plain; charset=iso-8859-1 Injection-Date: Thu, 06 Jun 2024 12:38:54 +0200 (CEST) Injection-Info: dont-email.me; posting-host="e7864bfc360e71a963a102a78e3bcf96"; logging-data="1558201"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/GdrZ6naW38szeXJHXxO6b" User-Agent: XanaNews/1.18.1.6 Cancel-Lock: sha1:06InufgmAtrETGEuyAqvVRWIgLA= Bytes: 1922 Pascal Bourguignon wrote: > > this simple function i'm trying to write is giving me headaches! > > basically i want to do something that does: > > (variations 'x '(y z)) -> ((x y z) (y x z) (y z x)) > > > > i come from a procedural programming background and find functional > > programming very confusing (especially recursion). can someone give > > me some hints? my attempts at this make no sense so pasting them here > > would only confirm my newbish forray into LSIP. thanks for any help! > > (defun variations (item list) > (if (null list) > (list (list item)) > (cons (cons item list) > (mapcar (lambda (rest) (cons (car list) rest)) > (variations item (cdr list)))))) Gauche Scheme: (use srfi-1) ;; split-at (use srfi-42) ;; list-ec (define (variations x lst) (list-ec (: i (+ 1 (length lst))) (receive (a b) (split-at lst i) `(,@a ,x ,@b)))) (variations '- '(a b c)) ===> ((- a b c) (a - b c) (a b - c) (a b c -)) (variations '- '(a)) ===> ((- a) (a -)) (variations '- '()) ===> ((-))