On Tue, 2008-09-16 at 11:00 -0700, William James wrote:
> On Aug 14, 9:08 am, vttoonses <·········@gmail.com> wrote:
> > On Aug 13, 9:36 am, Wang Jiaji <··········@gmail.com> wrote:
> >
> >
> >
> > > I'm reading Paul Graham's ANSI Common Lisp, there's a problem in the
> > > book which says:
> >
> > > 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:> (occurrences ' ( a b a d a c d e a ) )
> >
> > > ((A . 4) (C . 2) (D . 2) (B . 1))
> >
> > > So I wrote this:
> >
> > > (defun occurrence (list)
> > > (let ((results ()))
> > > (dolist (element list)
> > > (let ((times (cdr (assoc element results))))
> > > (if (null times)
> > > (push (cons element 1) results)
> > > (incf times))))
> > > (sort results #'> :key #'car)))
> >
> > > to my surprise this function always returns with only one occurrence:
> > > ((A . 1) (C . 1) (D . 1) (B . 1))
> >
> > > Could anybody tell me why? Thanks!
> >
> > Since it looks like you understand why this doesn't work and have come
> > up with a solution on your own, I'll show you what I did to solve this
> > problem:
> >
> > (defun occurrences (lst)
> > (and (consp lst)
> > (let ((result-list nil))
> > (mapcar #'(lambda (x)
> > (let ((pair (assoc x result-list)))
> > (if (null pair)
> > (push (cons x 1) result-list)
> > (incf (cdr pair)))))
> > lst)
> > (sort result-list #'> :key #'cdr))))
>
> Let's convert from ancient COBOL to modern Ruby.
>
> def occurrences array
> h = {} ; h.default = 0
> array.each{|x| h[x] += 1 }
> h.sort_by{|a| -a.last }
> end
great .. dumb _and_ persistent .. excellent combo
based on an educated guess, i think you'll do very well in your
country .. keep it up
--
Lars Rune Nøstdal || AJAX/Comet GUI type stuff for Common Lisp
http://nostdal.org/ || http://groups.google.com/group/symbolicweb