[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.lisp

re: tail recursion guidelines

William James

2/26/2016 4:39:00 AM

Peter Seibel wrote:

> > > > foreach i in (1..n)
> > > > if (multiple(i,3) or multiple(i,7)) count++
>
> > > In Common Lisp, this is preferrably expressed like so:
>
> > > (loop for i from 1 to n
> > > counting (or (multiple i 3) (multiple i 7)))
>
> > I tried your suggestion (I may as well experiment with iteration while
> > I'm at it), as follows, which worked fine:
>
> > (defun m37 (n)
> > (loop for i from 1 to n
> > counting (or (multiple i 3) (multiple i 7))))
>
> > So naturally now I'm wondering how this might be generalized to count
> > multiples of any list of numbers in any range. This seems like a very
> > Lispy thing to do, but I can't even guess at the syntax for doing
> > this:
>
> > (defun mult-list (start end nums-list)
> > (loop for i from start to end
> > counting (or (multiple i ??) (multiple i ??) (multiple i ??)
> > ...))))
>
> > where the '??' are the elements of the list 'nums-list'. There must be
> > something like mapcar that allows you to insert the elements of a list
> > into a pattern like this. Then I'd be able to count all the multiples
> > of 3, 5, or 7 between 1 and 1000 by entering
>
> > > (mult-list (1 1000 '(3 5 7)))
>
> (defun any-multiple-p (num nums-list)
> (loop for n in nums-list thereis (multiple num n)))
>
> (defun mult-list (start end nums-list)
> (loop for i from start to end
> counting (any-multiple-p i nums-list)))
>
> CL-USER(680): (mult-list 1 1000 '(3 5 7))
> 543

He failed to define "multiple".


MatzLisp (Ruby):

def multiple? n, m
n.modulo(m).zero?
end

def any_multiple? num, num_list
num_list.any?{|n| multiple? num, n}
end

def count_multiples first, last, num_list
first.upto(last).count{|i| any_multiple? i, num_list}
end

count_multiples 1, 1_000, [3,5,7]
===>
543


--
[W]e had enough employees who made more than 85 to fill all the openings. The
highest score that any of the blacks scored on the test was 11. The lowest
score that any black made on the test was 4. All four of those blacks went
into skilled-trades training.
https://archive.org/download/TheOldmanArchives/oldman29-...