Anonymous function

From TCS Wiki
Revision as of 05:21, 24 November 2013 by imported>Yejianfei (→‎C++ Boost)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

In computer science and mathematics, an anonymous function is a function that has no name. Usually, a function is written like: [math]\displaystyle{ f(x) = x^2 - x + 42 }[/math]. It can be written anonymously as [math]\displaystyle{ x \rightarrow x^2 - x + 42 }[/math] These are used in functional programming languages and other programming languages with support for anonymous functions (those which support 1st class functions).

Examples in some programming languages

Python

<source lang="python"> (lambda x: (lambda y: x * y)) </source>

The above code can be executed as a function:

<source lang="python"> >>>(lambda x: (lambda y: x * y))(3)(4) 12 </source>

Haskell

<source lang="haskell"> \x -> \y -> x * y </source>

The above code can be executed as a function:

<source lang="haskell"> (\x -> \y -> x * y) 3 4 </source>

The function can also be written in point-free (tacit) style: <source lang="haskell"> (*) </source>

Standard ML

Not curried: <source lang="ocaml"> fn (x, y) => x * y

(* or *)

(op * ) </source>

Curried: <source lang="ocaml"> fn x => fn y => x * y </source>

JavaScript

<source lang="javascript"> // uncurried function(x, y) {

   return x * y;

}

// curried function(x) {

   return (function(y)
   {
       return x * y;
   });

} </source>

Scheme

<source lang="scheme">

uncurried

(lambda (x y) (* x y))

usage

((lambda (x y) (* x y)) 3 4) (* 3 4)

curried

(lambda (x) (lambda (y) (* x y)))

usage

(((lambda (x) (lambda (y) (* x y))) 3) 4) </source>

C++ 11

Not curried: <source lang="cpp"> [](int x, int y)->int { return x * y; }; </source> Curried: <source lang="cpp"> [](int x) { return [=](int y)->int { return x * y; }; }; </source>

C++ Boost

<source lang="cpp"> _1 * _2 </source> Note: What you need to write boost lambda is to include <boost/lambda/lambda.hpp> header file, and using namespace boost::lambda, i.e. <source lang="cpp">

  1. include <boost/lambda/lambda.hpp>

using namespace boost::lambda; </source>

You can call it as: (_1 * _2)(3, 4) to get 12.

Related pages

Other websites


Template:Tech-stub