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: .Re: simple lisp function Date: Thu, 6 Jun 2024 23:31:05 -0000 (UTC) Organization: A noiseless patient Spider Lines: 53 Message-ID: References: MIME-Version: 1.0 Content-Type: text/plain; charset=iso-8859-1 Injection-Date: Fri, 07 Jun 2024 01:31:06 +0200 (CEST) Injection-Info: dont-email.me; posting-host="0664cbc0701e7189d76401c36ed24bc2"; logging-data="1821181"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18beMOgP8s0oNDZWG1nira4" User-Agent: XanaNews/1.18.1.6 Cancel-Lock: sha1:kwuvhThgNugHTYyiZpJE9vjcAhk= Bytes: 2311 On 6/6/2024, B. Pym wrote: > 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 '- '()) > ===> > ((-)) > Gauche or Racket Scheme: (use srfi-42) ;; list-ec for Gauche or (require srfi/42) ;; list-ec for Racket (define (variations item seq) (list-ec (: i (+ 1 (length seq))) `(,@(take seq i) ,item ,@(drop seq i))))