Skip to content

Lambda abstraction

Wang Renxin edited this page Jan 9, 2016 · 18 revisions

According to Uncyclopedia's description, a Lambda abstraction (aka. anonymous function or function literal) is a function definition that is not bound to an identifier. Lambda functions are often:

  1. Arguments being passed to higher order functions, or
  2. Used for constructing the result of a higher-order function that needs to return a function.

A Lambda becomes a closure after it captured some values in outer scope.

MY-BASIC has a full support for Lambda, including invokable as a value, higher order function, closure and currying, etc.

The lambda syntax in MY-BASIC is:

LAMBDA ::= lambda "(" PARAMETERS ")" "(" BODY ")"
PARAMETERS ::= variable { "," PARAMETERS }
BODY ::= STATEMENTS
STATEMENTS ::= statement \n STATEMENTS

It begins with a LAMBDA keyword, and follows by a parameter list (with none or multiple parameter identifiers), and the lambda body. It's able to write multiple line statements in a lambda body, use the RETURN statement to return a value in the lambda body. Let's have a look at some short samples as follow.

Simple invoke:

f = lambda (x, y) (return x * x + y * y)
print f(3, 4);

Return as a value:

def counter()
	c = 0

	return lambda (n)
	(
		c = c + n
		print c;
	)
enddef

acc = counter()

acc(1)
acc(2)

Higher order function:

def foo()
	y = 1

	return lambda (x, z) (return x + y + z)
enddef

l = foo()

print l(2, 3);

Closure:

s = 0

def create_lambda()
	v = 0

	return lambda ()
	(
		v = v + 1
		s = s + 1
		print v;
		print s;
	)
enddef

a = create_lambda()
b = create_lambda()

a()
b()

Currying:

def divide(x, y)
	return x / y
enddef

def divisor(d)
	return lambda (x) (return divide(x, d))
enddef

half = divisor(2)
third = divisor(3)

print half(32); third(32);

It's extraordinary neat to implement a foreach loop with lambda:

def foreach(c, f)
	it = iterator(c)
	while move_next(it)
		item = get(it)
		f(item)
	wend
enddef

f = lambda (i) (print i;)

l = list(1, 2, 3, 4)

foreach(l, f)
Clone this wiki locally