[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.lisp

Re: I would appreciate a code review

William James

3/2/2016 6:27:00 PM

> > through Paul Graham's ANSI Common Lisp book.
> >
> > This is my code followed by my test cases for Exercise 3 on p. 56 of
> > that book.
> >
> > <QOUTE>
> > Define a function that takes a list and returns a list indicating the
> > number of times each (eql) element appears, sorted from most common
> > element to least common.
> >
> > >(occurences '(a b a d a c d c a))
> > ((A . 4) (C . 2) (D . 2) (B . 1))
> > </QUOTE>
....
> (defun occurrences (list &key (test #'eql)) ;#1
> (let ((alist '()))
> (dolist (item list)
> (incf (cdr (or (assoc item alist :test test)
> (let ((entry (cons item 0)))
> (push entry alist)
> entry)))))
> (sort alist #'> :key #'cdr)))

SML:

val rec update_counts = fn
(key, []) => [(key,1)]
| (key, (entry as (k,v))::rest) =>
if k=key then (k,v+1)::rest
else entry::(update_counts (key, rest))

fun occurrences list =
sort (fn ((_,n1),(_,n2)) => n1<n2)
(foldl update_counts [] list) ;

occurrences ["a", "b", "a", "d", "a", "c", "d", "c", "a"];
===>
[("a",4),("d",2),("c",2),("b",1)]


--
Amazon bans book. After nearly a month on the site, all traces of the book and
its 80 reviews have been removed.
http://jamesfetzer.blogspot.com/2015/11/debunking-sandy-hook-debunk...
https://www.youtube.com/watch?v=E...