Finding the minimum element in a list

Discussion of Common Lisp
Indecipherable
Posts: 47
Joined: Fri Jun 03, 2011 5:30 am
Location: Behind you.
Contact:

Re: Finding the minimum element in a list

Post by Indecipherable » Tue Jun 21, 2011 10:22 am

Not really in a loop, but I guess it can be put inside it :?

Code: Select all

(defun min-list (mlist)
   (eval `(min ,@mlist)))
Don't take the FUN out of DEFUN !

Paul
Posts: 106
Joined: Tue Jun 02, 2009 6:00 am

Re: Finding the minimum element in a list

Post by Paul » Wed Jun 22, 2011 3:18 am

Indecipherable wrote:Not really in a loop, but I guess it can be put inside it :?

Code: Select all

(defun min-list (mlist)
   (eval `(min ,@mlist)))
No. Just, no!

gugamilare
Posts: 406
Joined: Sat Mar 07, 2009 6:17 pm
Location: Brazil
Contact:

Re: Finding the minimum element in a list

Post by gugamilare » Wed Jun 22, 2011 3:52 pm

Indecipherable wrote:Not really in a loop, but I guess it can be put inside it :?

Code: Select all

(defun min-list (mlist)
   (eval `(min ,@mlist)))
As a rule of thumb, don't use eval unless what you are doing really needs an evaluator (e.g. if you are generating functions on-the-fly or if you need an interpreter of some sort).

Konfusius
Posts: 62
Joined: Fri Jun 10, 2011 6:38 am

Re: Finding the minimum element in a list

Post by Konfusius » Tue Jun 28, 2011 7:47 am

Why not? It's perfectly legal and correct code. Using

Code: Select all

(defun min-list (mlist)
   (apply #'min mlist))
would be more efficient, though.

gugamilare
Posts: 406
Joined: Sat Mar 07, 2009 6:17 pm
Location: Brazil
Contact:

Re: Finding the minimum element in a list

Post by gugamilare » Tue Jun 28, 2011 8:37 am

It's slow, ugly and unnecessary. Also, Lispers who view your code will think you couldn't find a better way to deal with the problem because, in general, using eval when not needed is very common among newbies.

It would be more efficient to use reduce instead of apply (it has already been said in this thread) because, in general, it is faster to call functions with only two arguments then with many arguments. Not to mention that there is a limit on the number of arguments a function can take, so reduce would work more generally.

nuntius
Posts: 538
Joined: Sat Aug 09, 2008 10:44 am
Location: Newton, MA

Re: Finding the minimum element in a list

Post by nuntius » Tue Jun 28, 2011 7:39 pm

EVAL is something like the UUOC of the lisp world...

Post Reply