William James
12/4/2015 4:48:00 AM
WJ wrote:
> WJ wrote:
>
> > WJ wrote:
> >
> > > Wade Humeniuk wrote:
> > >
> > > > > > I came right back here when I realized that
> > > > > > (defun find-maximizing-item (list fun)
> > > > > > (reduce #'max list :key fun))
> > > > > > was what I was originally looking for, but I see you beat me to it.
> > > > > +---------------
> > > > >
> > > > > Except that only tells you what the maximum function value was,
> > > > > not which item produced it! [...which is what I thought the original
> > > > > question was.] That is, with this version:
> > > > >
> > > > > > (find-maximizing-item '(3 -4 2 5 -7 1 2) (lambda (x) (* x x)))
> > > > >
> > > > > 49
> > > > > >
> > > > >
> > > > > doesn't tell you it was the "-7" that caused this result.
> > > > >
> > > >
> > > > Which is remedied by,
> > > >
> > > > (defun find-maximizing-item (list fun)
> > > > (values-list
> > > > (reduce (lambda (e1 e2) (if (> (car e1) (car e2)) e1 e2))
> > > > list :key (lambda (elt) (list (funcall fun elt) elt)))))
> > > >
> > > > CL-USER 4 > (find-maximizing-item '(3 -4 2 5 -7 1 2) (lambda (x) (* x x)))
> > > > 49
> > > > -7
> >
> > Ocaml:
> >
>
>
> open List;;
>
>
>
> > let find_maximizing_item func list =
> > let rec loop best = function
> > [] -> best
> > | x::xs -> loop (max (func x, x) best) xs
> > in loop (func (hd list), hd list) (tl list) ;;
> >
> >
> > find_maximizing_item (fun x -> x*x) [3;-4;2;5;-7;1;2];;
> > ===>
> > (49, -7)
Also works with floats and strings:
# find_maximizing_item (fun x -> x*.x) [3.;-4.;2.;5.;-7.;1.;2.];;
- : float * float = (49., -7.)
# find_maximizing_item String.lowercase ["cow";"ZOO";"how"];;
- : string * string = ("zoo", "ZOO")