Lambda Functions & Closures A Sydney PHP Group Presentation 2 nd October 2008 By Timothy Chandler.

Slides:



Advertisements
Similar presentations
Lecture 9: More on objects, classes, strings discuss hw3 assign hw4 default values for variables scope of variables and shadowing null reference and NullPointerException.
Advertisements

C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Chapter 9 Subprograms Sections 1-5 and 9. Copyright © 2007 Addison-Wesley. All rights reserved. 1–2 Introduction Two fundamental abstraction facilities.
Road Map Introduction to object oriented programming. Classes
1 Lecture 18:User-Definded function II(cont.) Introduction to Computer Science Spring 2006.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Names and Scopes CS 351. Program Binding We should be familiar with this notion. A variable is bound to a method or current block e.g in C++: namespace.
School of Computing Science CMT1000 © Ed Currie Middlesex University Lecture 10: 1 TEST!!
Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York University.
Catriel Beeri Pls/Winter 2004/5 environment 68  Some details of implementation As part of / extension of type-checking: Each declaration d(x) associated.
The environment of the computation Declarations introduce names that denote entities. At execution-time, entities are bound to values or to locations:
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Java Review 2 – Errors, Exceptions, Debugging Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Javascript II Expressions and Data Types. 2 JavaScript Review programs executed by the web browser programs embedded in a web page using the script element.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointer Data Type and Pointer Variables
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
Functional Programming Universitatea Politehnica Bucuresti Adina Magda Florea
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Object Oriented Programming in PHP. Topics Quick OOP Review Classes Magic Methods Static Methods Inheritance Exceptions Interfaces Operators Type Hinting.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
OOP IN PHP `Object Oriented Programming in any language is the use of objects to represent functional parts of an application and real life entities. For.
C# EMILEE KING. HISTORY OF C# In the late 1990’s Microsoft recognized the need to be able to develop applications that can run on multiple operating system.
Object Oriented Software Development
Visual C# 2012 for Programmers © by Pearson Education, Inc. All Rights Reserved.
COMP3190: Principle of Programming Languages
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
C++ Programming Lecture 11 Functions – Part III By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
KIC/Computer Programming & Problem Solving 1.  Header Files  Storage Classes  Scope Rules  Recursion Outline KIC/Computer Programming & Problem Solving.
Variables, Environments and Closures. Overview Touch on the notions of variable extent and scope Introduce the notions of lexical scope and dynamic.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Pointers.
1 Chapter 6 Methods. 2 Motivation Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.
FEN 2014UCN Teknologi/act2learn1 Higher order functions Observer Pattern Delegates Events Visitor Pattern Lambdas and closures Lambdas in libraries.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
21. PHP Classes To define a class, use the keyword class followed by the name and a block with the properties and method definitions Properties are declared.
MIT-AITI: Functions Defining and Invoking Functions Functions as Data Function Scope: The call Object Function Arguments: The arguments objects Function.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
PHP Reusing Code and Writing Functions 1. Function = a self-contained module of code that: Declares a calling interface – prototype! Performs some task.
FIT Objectives By the end of this lecture, students should: understand the role of constructors understand how non-default constructors are.
 Static  Example for Static Field  Example for Static Method  Math class methods  Casting  Scope of Declaration  Method Overloading  Constructor.
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Martin Kruliš by Martin Kruliš (v1.0)1.
Procedure Definitions and Semantics Procedures support control abstraction in programming languages. In most programming languages, a procedure is defined.
C# Fundamentals An Introduction. Before we begin How to get started writing C# – Quick tour of the dev. Environment – The current C# version is 5.0 –
1 This week Basics of functions Stack frames Stack vs. Heap (brief intro) Calling conventions Storage classes vs. scope Library functions Overloading.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Recap Resizing the Vector Push_back function Parameters passing Mechanism Primitive Arrays of Constants Multidimensional Arrays The Standard Library string.
Heath Carroll Bill Hanczaryk Rich Porter.  A Theory of Type Polymorphism in Programming ◦ Robin Milner (1977)  Milner credited with introducing the.
Chapter 7: User-Defined Functions II
Java Primer 1: Types, Classes and Operators
University of Central Florida COP 3330 Object Oriented Programming
Road Map Introduction to object oriented programming. Classes
Generics, Lambdas, Reflections
Using local variable without initialization is an error.
Variables, Environments and Closures
Object Oriented Programming in java
BBIT 212/ CISY 111 Object Oriented Programming (OOP)
Classes and Objects Imran Rashid CTO at ManiWeber Technologies.
Creating and Using Classes
Chengyu Sun California State University, Los Angeles
Presentation transcript:

Lambda Functions & Closures A Sydney PHP Group Presentation 2 nd October 2008 By Timothy Chandler

Lambda Functions – Lambda Calculus Lambda functions originate from lambda calculus which was introduced by Alonzo Church and Stephen Cole Kleene in the 1930s. The lambda calculus can be thought of as an idealized, minimalistic programming language. It is capable of expressing any algorithm, and it is this fact that makes the model of functional programming an important one. The lambda calculus provides the model for functional programming. Modern functional languages can be viewed as embellishments to the lambda calculus.

Lambda Functions – Implementations Implementing the lambda calculus on a computer involves treating "functions" as “first-class objects”, which raises implementation issues for stack-based programming languages. This is known as the Funarg problem – More on this later. Many languages implement lambda functions. These include: Python C++ C# (2 different implementations – Second one improved in C# v3.0) JavaScript...and many more...

Lambda Functions – Implementation Examples Python: C++: s Python Lambda Function func = lambda x: x ** 2 s C++ Lambda Function std::for_each(c.begin(), c.end(), std::cout << _1 * _1 << std::endl);

Lambda Functions – Implementation Examples C#: C# v3.0: s C# v3.0 Lambda Function //Create an delegate instance MathDelegate lambdaFunction = i => i * i; Execute(lambdaFunction); s C# Lambda Function //Declare a delegate signature delegate double MathDelegate(double i); //Create a delegate instance MathDelegate lambdaFunction = delegate(double i) { return Math.Pow(i, 2); }; /* Passing ' lambdaFunction ' function variable to another method, executing, and returning the result of the function */ double Execute(MathDelegate lambdaFunction) { return lambdaFunction(100); }

Lambda Functions – Implementation Examples JavaScript: s JavaScript Lambda Function var lambdaFunction=function(x) { return x*10; } document.write(lambdaFunction(100));

Lambda Functions – The PHP Way PHP 5.3: Syntax: s PHP 5.3 Lambda Function <?php $lambdaFunction=function($x) { return $x*10; }; print $lambdaFunction(100); ?> s Lambda Function Syntax function & (parameters) use (lexical vars) { body };

Lambda Functions – The PHP Way The goal of PHP’s Lambda function implementation is to allow for the creation of quick throw-away functions. Don’t confuse with “create_function()”. These functions compile at “run-time”. These functions DO NOT compile at “compile-time”. Optcode caches CANNOT cache them. Bad practice.

Closures

Closures – The Funarg Problem Lambda functions MUST be first-class objects. Funarg, meaning “functional argument”, is a problem in computer science where a “stack-based programming language” has difficulty implementing functions as “first-class objects”. The problem is when the body of a function refers to a variable from the environment that it was created but not the environment of the function call. Standard Solutions: Forbid such references. Create closures.

Closures – The PHP Funarg Problem Solution PHP 5.3 introduces a new keyword ‘use’. Use this new keyword when creating a lambda function to define what variables to import into the lambda functions scope – This creates a Closure.

Closures – The “use” Keyword Example: Result: s Lambda Function Closure $config=array('paths'=>array('examples'=>'c:/php/projects/examples/')); $fileArray=array('example1.php','example2.php','exampleImage.jpg'); $setExamplesPath=function($file) use($config) { return $config['paths']['examples'].$file; }; print_r(array_map($setExamplesPath,$fileArray) ); Array ( [0] => c:/php/projects/examples/example1.php [1] => c:/php/projects/examples/example2.php [2] => c:/php/projects/examples/exampleImage.jpg )

Closures – The “use” Keyword Example: Result: s Lambda Function Closure – As an Anonymous Function $config=array('paths'=>array('examples'=>'c:/php/projects/examples/')); $fileArray=array('example1.php','example2.php','exampleImage.jpg'); print_r(array_map ( function($file) use($config) { return $config['paths']['examples'].$file; }, $fileArray )); Array ( [0] => c:/php/projects/examples/example1.php [1] => c:/php/projects/examples/example2.php [2] => c:/php/projects/examples/exampleImage.jpg )

Closures – “use” as reference or copy Variables passed into the “use” block are copied in by default – This is the expected PHP behaviour. You can cause a variable to be imported by reference the same way you do when defining referenced parameters in function declarations. The PHP 5 pass by reference for objects rule still applies.

Closures – “use” by reference Example: Why? Able to directly affect the variable from within the lambda function. If used with a large array, can prevent massive overheads. Memory efficient. s Referenced Variable Import

Lifecycle A lambda function can be created at any point in your application, except in class declarations. Example: Throws Error: s Lambda Function in Class Declaration class foo { public $lambda=function() { return 'Hello World'; }; public function __construct() { print $this->lambda(); } new foo(); Parse error: syntax error, unexpected T_FUNCTION in D:\Development\www\php5.3\lambda\5.php on line 4

Lambda functions can live longer than whatever created them. Example: Result: s Lifecycle Example 1 class foo { public $lambda=null; public function __construct() { $this->lambda=function() {return 'Hello World';}; } $foo=new foo(); var_dump($foo); $lambda=$foo->lambda; unset($foo); var_dump($foo); print $lambda(); Lifecycle object(foo)#1 (1) { ["lambda"]=> object(Closure)#2 (0) { } } NULL Hello World

Imported variables can also live longer. Example: Result: s Lifecycle Example 2 //Create prefix say function. $say=function($prefix) { return function($suffix) use(&$prefix) { print $prefix.$suffix; }; //Create suffix say function - will loose $prefix right? $say=$say('Hello '); //Wrong! - Execute new say concatenated function. $say('World!'); //Outputs "Hello World!" Lifecycle Hello World

Methods and properties used in a closure can live longer than the object. Example: Result: s Lifecycle Example 3 class foo { public $bar="Bar\r\n"; public function __construct(){print "__construct()\r\n“;} public function __destruct(){print "__destruct()\r\n“;} public function getBarLambda() { return function(){return $this->bar;}; } $foo=new foo(); $bar=$foo->getBarLambda(); print $bar(); unset($foo); var_dump($foo); print $bar(); unset($bar); print $bar(); Lifecycle – Objects __construct() Bar NULL Bar __destruct() Fatal error Function name must be a string in D:\Development\www\php5.3\lambda\8.php on line 31

If a closure exists with a reference to an object’s method or property, that object is not completely destroyed when unset. __destruct() is NOT called until the closure is destroyed. The unset object CANNOT be used in this situation as it will be considered a null value by anything trying to access it outside the closure environment. Lifecycle – Objects

Lambda Functions are Closures because they automatically get bound to the scope of the class that they are created in. $this is not always needed in the scope. Removing $this can save on memory. You can block this behaviour by declaring the Lambda Function as static. Object Orientation

Example: Result: s Static Lambda Functions class foo { public function getLambda() { return function(){var_dump($this);}; } public function getStaticLambda() { return static function(){var_dump($this);}; } $foo=new foo(); $lambda=$foo->getLambda(); $staticLambda=$foo->getStaticLambda(); $lambda(); $staticLambda(); object(foo)#1 (0) { } NULL

PHP 5.3 introduces a new magic method. Invokable objects are now possible through the use of the __invoke() magic method. Essentially makes the object a closure. Object Orientation

Example: Result: s Invokable Objects class foo { public function __invoke() { print 'Hello World'; } $foo=new foo; $foo(); Hello World

Questions?

Thank you. References