Jump to content

How are anonymous functions used?

- - - - -

  • Please log in to reply
3 replies to this topic

#1
DarkLordofthePenguins

DarkLordofthePenguins

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 409 posts
The Wikipedia article for anonymous functions gives this code in Python:


a = [10, '10', 10.0]

a.sort(lambda x,y: cmp(x.__class__.__name__, y.__class__.__name__))

print a

[10.0, 10, '10']


Okay, this doesn't make sense. How do you pass the parameters x and y to the anonymous function? Nowhere in the code does it specify what x and y actually are, or what their values are, or where their values came from.

Also, I've tried using the lambda operator in a Lisp program to conditionally build a function:


( defun fun ()

	( cond

		( ( > var 0 ) ( lambda () ( print "p" ) ) )

		( ( < var 0 ) ( lambda () ( print "n" ) ) )

		( t ( lambda () ( print "z" ) ) ) ) ) )


This evaluates to "FUN", and when I run the function it does nothing (I already declared var by the way).

So what exactly do anonymous functions do? What are they used for, how are they called, and how are parameters passed to them? Can you give me some example code (preferably in Lisp)?
Programming is a journey, not a destination.

#2
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others
It looks like sort accepts a single parameter, a lambda function, and implicitly does pairwise comparison of the elements in array a. So the actual calls of the lambda function are buried in the sort method.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#3
DarkLordofthePenguins

DarkLordofthePenguins

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 409 posts
I still don't get it. My Lisp book says that lambda forms aren't evaluated. What's the point of a function that isn't evaluated? What does it do?
Programming is a journey, not a destination.

#4
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others
In Lisp, lambda functions can be passed as functions to be called on parameters, depending on how it's defined. I'd have to dig into my Lisp book, as I haven't looked at it in nearly a year.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users