Rocksolid Light

Welcome to RetroBBS

mail  files  register  newsreader  groups  login

Message-ID:  

The world is no nursery. -- Sigmund Freud


devel / comp.lang.lisp / .Re: ACL - Chpater 2, Exercise 9

SubjectAuthor
o .Re: ACL - Chpater 2, Exercise 9Robert L.

1
.Re: ACL - Chpater 2, Exercise 9

<suukbh$3qf$1@gioia.aioe.org>

  copy mid

https://www.rocksolidbbs.com/devel/article-flat.php?id=16912&group=comp.lang.lisp#16912

  copy link   Newsgroups: comp.lang.lisp
Path: i2pn2.org!i2pn.org!aioe.org!cnMFwgAl3AZSZhKJg9s53w.user.46.165.242.75.POSTED!not-for-mail
From: No_spamming@noWhere_7073.org (Robert L.)
Newsgroups: comp.lang.lisp
Subject: .Re: ACL - Chpater 2, Exercise 9
Date: Sun, 20 Feb 2022 23:54:26 -0000 (UTC)
Organization: Aioe.org NNTP Server
Message-ID: <suukbh$3qf$1@gioia.aioe.org>
Mime-Version: 1.0
Content-Type: text/plain; charset=iso-8859-1
Injection-Info: gioia.aioe.org; logging-data="3919"; posting-host="cnMFwgAl3AZSZhKJg9s53w.user.gioia.aioe.org"; mail-complaints-to="abuse@aioe.org";
User-Agent: XanaNews/1.18.1.6
X-Notice: Filtered by postfilter v. 0.9.2
 by: Robert L. - Sun, 20 Feb 2022 23:54 UTC

Tamas Papp wrote:

> On Wed, 14 Dec 2011 12:34:12 +0000, arnuld wrote:
>
> > EXERCISE STATEMENT: A friend is trying to write a function that returns
> > the sum of all non-nil elements in the given list. He has written two
> > versions of this function, and neither of them works. Explain what is
> > wrong with each and give a correct version:
> >
> > 1. (defun summit (lst)
> > (remove nil lst)
> > (apply #'+ lst))
> >
> > 2. (defun summit (lst)
> > (let ((x (car lst)))
> > (if (null x)
> > (summit (cdr lst))
> > (+ x (summit (cdr lst)))))
> >
> >
> > 1st version has problem that (remove) never modifies the original list.
> > Hence the correct version will be one-liner: (apply #'+ (remove nil
> > lst))
> >
> >
> > 2. CLISP says "*** Program Stack Overflow . RESET" . Oh.. let me see,
> > Recursion never bottoms out and hence it hits the stack limit. But then
> > how to write a correct version which take care of nil atoms and bottoms
> > out too ?
> >
> > IDEA: rather than setting x to (car lst) and checking for null, we can
> > keep on doing cdr till the end and when we will hit nil it means we have
> > reached the last atom of list, from there onwards we can add values,
> > tail- recursion. I am unable to implement it though
> >
> > Is it correct way ?
>
> I don't know what correct means in this context, but perhaps a more
> idiomatic way would be to use REDUCE, treating NIL as 0. Eg
>
> (defun summit (sequence)
> "Sum non-nil elements of SEQUENCE."
> (reduce #'+ sequence :key (lambda (element)
> (if (null element)
> 0
> element))))
>

Gauche Scheme or Racket:

(require srfi/1) ;; fold for Racket

(define (summit seq)
(fold
(lambda (x sum) (+ (or x 0) sum))
0
seq))

(summit '(1 3 5 7 #f 9))
===>
25


devel / comp.lang.lisp / .Re: ACL - Chpater 2, Exercise 9

1
server_pubkey.txt

rocksolid light 0.9.81
clearnet tor