> > > (defn maximal-elements [f s]
> > >  "Return a seq of elements of s maximizing (f elt)."
> > >  (when (seq s)
> > >    (loop [max-elts (first s),
> > >           max-val (f (first s)),
> > >           rest-elts (rest s)]
> > >      (if (empty? rest-elts)
> > >          max-elts
> > >        (let [next-val (f (first rest-elts))]
> > >          (cond (< next-val max-val) (recur max-elts max-val (rest rest-
> > > elts))
> > >                (= next-val max-val) (recur (cons (first rest-elts) 
> > > max-elts) max-
> > > val (rest rest-elts))
> > >                (> next-val max-val) (recur [(first rest-elts)] next-val 
> > > (rest rest-
> > > elts))))))))
>
> > I'm having a hard time imagining when maximal-elements would be
> > useful.  What have you used it for?  Looks like a good candidate for
> > application code. :-)
>
> I've used it for picking the best successors in a search algorithm,
> particularly as (first (maximal-elements ...)) or (random-element
> (maximal-elements ...)).
>
> But, I can imagine it would be useful in many situations, i.e. things
> like.
> user> (maximal-elements second {:bob 10 :lisa 20 :peter 20})
> ([:peter 20] [:lisa 20])


Oops, just found occasion to use this again and realized there's a bug
if the first element ends up being maximal.  Here's a fixed version.

(defn maximal-elements [f s]
  "Return a seq of elements of s maximizing (f elt)."
  (when (seq s)
    (loop [max-elts [(first s)],
           max-val (f (first s)),
           rest-elts (rest s)]
      (if (empty? rest-elts)
          max-elts
        (let [next-val (f (first rest-elts))]
          (cond (< next-val max-val) (recur max-elts max-val (rest rest-
elts))
                (= next-val max-val) (recur (cons (first rest-elts) max-elts) 
max-
val (rest rest-elts))
                (> next-val max-val) (recur [(first rest-elts)] next-val (rest 
rest-
elts))))))))



--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Clojure" group.
To post to this group, send email to clojure@googlegroups.com
To unsubscribe from this group, send email to 
clojure+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/clojure?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to