Realizing C++11 Lambda Expression in Open64

Total Page:16

File Type:pdf, Size:1020Kb

Realizing C++11 Lambda Expression in Open64 Realizing C++11 Lambda Expression in Open64 Javed Absar Anitha Boyapati Dibyendu Das AMD, India AMD, India AMD, India Richmond Road Richmond Road Richmond Road Bangalore Bangalore Bangalore +91 9901880710 +91 7795334034 +91 9448537014 [email protected] [email protected] [email protected] ABSTRACT higher-order functions. Higher order functions are functions that C++11 is the latest edition of C++ programming language take one or more functions as input and output a function as standard by ISO. It replaces C++03. It includes a number of core return value [4]. Their major use is to abstract common behaviour language extensions, probably the most interesting of which is the into one place [5]. inclusion of the lambda-expressions. The onus is now upon Higher order functions are closely related to first-class functions. compiler writers – gcc, llvm, Open64 and others, to incorporate The distinction between the two is that higher-order function this extension into their existing compiler infrastructure so that describes a mathematical concept while first-class object is a programmers could benefit from this powerful language feature. computer science term that describes programming language Incorporating lambda-expression is not so straight-forward an entity that has no restriction on its use. First-class functions can extension for a compiler. It needs a good understanding of the therefore appear anywhere in the program where other first-class C++11 standard and the many possible intricate use and misuse of entities such as numbers can appear, including as arguments to this language feature in programs. In this paper, we analyze other functions and as the return value. lambda expression from a language-feature perspective, the value it provides to programmers and how Open64 could support it. In mathematics, higher order functions are also known as operators . For example, the definite integral in calculus is an operator that given a function f of a real variable x, and an interval Categories and Subject Descriptors [a, b] on the real line, returns the area under its curve. Later we D.3.4 [Programming Languages ]: Processors – compilers. will illustrate implementation of this operator using anonymous- function construct of C++11. General Terms Anonymous function and lambda-expression are sometimes used Algorithms, Design, Languages and Theory. in a mixed and confusing way, more so in programming language contexts than in mathematical expositions. In mathematics, Keywords lambda-expression is a notational convention in support of lambda expression, anonymous function, C++11, C++0x, closure, lambda calculus. Lambda expression in programming is an higher order function, Open64, WHIRL, compiler. expression that specifies an anonymous function object [6]. Since anonymous functions in programming languages can have statements (control, assignment or expression statement) in the 1. INTRODUCTION function body, the mathematical purity is lost to some extent. The first programming language to adopt anonymous functions C++11 [1] was approved by the ISO in August 2011 as the new was Lisp (1958). Traditionally anonymous functions have found standard for the C++ programming language, replacing C++03. good use in functional languages and languages that treat The name C++11 is derived from the convention of naming functions as first-class objects, such as Haskell, Scheme, ML and language versions based on the year of publication. Lisp [7][8]. In the current era of multi-paradigm languages, many C++11 includes several addition to the core language. In the imperative, procedural and object-oriented languages have added design of C++11 standard, the committee had applied some anonymous class and anonymous functions to their repertoire of directives to help guide their decision. One of the directives was language features – C#, Clojure, Java, JavaScript, PHP, amongst “to prefer changes that can evolve programming technique”. The others. C++ added anonymous function in its C++11 edition. inclusion of anonymous functions or lambda function is a direct Support for anonymous function in C# (.NET) [9] has improved result of that objective. with new versions of the compiler. In C# 1.0, one would create an Anonymous function is a function which is defined and invoked instance of a delegate by explicitly initializing it with a method without being bound to an identifier. Anonymous functions have that was defined elsewhere in the code. In C# 2.0, a delegate their origin in the works of Alonzo Church on λ-calculus [2][3]. could be initialized with inline code, called anonymous method. They are a convenient way to pass functions as arguments to In C# 3.0, a delegate could be initialized with a lambda expression, which is more expressive and concise. E.g. in 2.0 the Permission to make digital or hard copies of all or part of this work for personal or parameter type had to be defined twice (during declaration of classroom us e is granted without fee provided that copies are not made or distributed for profit or commercial advantage and that copies bear this notice and the full citation delegate and during initialization) and this was done away in 3.0. on the first page. To copy otherwise, or republish, to post on servers or to redistribute to lists, requires prior specific permission and/or a fee. PLDI’12 . Copyright © 2012 ACM 1 -59593 -XXX -X/0X/000X…$5.00. C++11 has leapfrogged this by removing most redundancies seen in earlier versions of C# and gives a spartan expression of anonymous function definition and invocation. Anonymous functions discussion requires an understanding of the concept of closure. A closure is a function together with a referencing environment for the non-local variables of the function. Or to quote the ISO/IEC sub-committee technical report [9], “ Closure is an anonymous function object that is created automatically by the compiler as a result of evaluating a lambda expression. Closure consists of the code of the body of the lambda function and the environment in which the lambda function is Figure 1. Computing definite integral by partitioning the area defined ”. In practice, this means that external variables referred to under the curve into rectangles in the body are stored (as reference or as copied-value) as member variables of the anonymous function object. Or that a pointer to the frame where the lambda function was created is stored in the The key limitation here is that the pointed-to function ptr2func function object. has to be defined separately from the context in which integrate will be called from. Suppose we need to compute integral of f(x) The concept of closure was developed in 1960s and featured in = u/x+v. We define it as below and then pass a pointer to Scheme programming. C++11 support closures in two default func_inverse each time we need to integrate f (x) = u/x+v. forms. One stores a copy of the variable, the other stores references to the original variables. Both provide functionality to override this default behaviour for individual variables. double func_inverse(double x ) { A key limitation of the C++11 lambda feature, however, is that return u/x+v; C++11 closures are monomorphic . That is, their type does not } adapt to the context in which they are called. This is unlike C#. 2. Organization of the Paper Different contexts from which integrate may be called may have different values of u and v. To overcome this problem, we are forced to set u and v as globals, a highly undesirable solution. In Sec 3, we provide the advantages of using anonymous function. Sec 4 discusses the formal syntax and semantics of C++11 lambda-expression illustrating key concepts with examples. Sec 5 3.2 Integral – Function Object gets into the details of implementing anonymous function in the front-end and in Open64 [12]. Sec 6 forms the conclusion. In C++ prior to C++11, we can use function object or functor to solve the same integral problem in a more elegant manner. A 3. Lambda Expression – Motivation functor is a construct that allows an object to be called as if it were a function. We construct a class (e.g. CFoo ) which overloads In this section, we illustrate with examples the advantages of the function call operator ( ) member function. In C++ this is C++11 lambda functions over other forms of expression – such as called class type functor. function pointers of C and object function of C++03. 3.1 Integral – Function Pointers class CFoo{ public: double u,v; Consider the problem of writing a function to compute the definite integral [a,b] of a mathematical function f : R→R. The basic double operator( )(double x){ return u/x+v; } approach is to divide the area under the curve of f into very }; narrow rectangles and sum the area of all the rectangles. The double integrate( double a, double b, CFoo f){ integrate function is then actually a higher-order function as it int i; double sum =0, dt = (b-a)/N; takes not a value but any continuous function as its input. for( int i = 0 ; i < N; i++ ) sum += f(a+i*dt)*dt;… Now, if we limit ourselves to implementing integral in C, we can use function pointer as shown below. return sum; } int main( ){ double integrate(double a, double b, double (*ptr2func)(double) ) CFoo f_inv_x; { f_inv_x.u = … ; f_inv_x.v = …; double a=… b =…; int i; double sum =0, dt = (b-a)/N; // N is number of segments double t = integrate (a, b, f_inv_x); … for( i = 0; i < N; i++ ) sum += ptr2func(a+i*dt) * dt ; } return sum; Figure 2 Computing definite integral using functor } The code above demonstrates how the idiom of functor is double t = integrate (a, b, [u,v ](double x){ return u/x+v;} ); typically used.
Recommended publications
  • Higher-Order Functions 15-150: Principles of Functional Programming – Lecture 13
    Higher-order Functions 15-150: Principles of Functional Programming { Lecture 13 Giselle Reis By now you might feel like you have a pretty good idea of what is going on in functional program- ming, but in reality we have used only a fragment of the language. In this lecture we see what more we can do and what gives the name functional to this paradigm. Let's take a step back and look at ML's typing system: we have basic types (such as int, string, etc.), tuples of types (t*t' ) and functions of a type to a type (t ->t' ). In a grammar style (where α is a basic type): τ ::= α j τ ∗ τ j τ ! τ What types allowed by this grammar have we not used so far? Well, we could, for instance, have a function below a tuple. Or even a function within a function, couldn't we? The following are completely valid types: int*(int -> int) int ->(int -> int) (int -> int) -> int The first one is a pair in which the first element is an integer and the second one is a function from integers to integers. The second one is a function from integers to functions (which have type int -> int). The third type is a function from functions to integers. The two last types are examples of higher-order functions1, i.e., a function which: • receives a function as a parameter; or • returns a function. Functions can be used like any other value. They are first-class citizens. Maybe this seems strange at first, but I am sure you have used higher-order functions before without noticing it.
    [Show full text]
  • Typescript Language Specification
    TypeScript Language Specification Version 1.8 January, 2016 Microsoft is making this Specification available under the Open Web Foundation Final Specification Agreement Version 1.0 ("OWF 1.0") as of October 1, 2012. The OWF 1.0 is available at http://www.openwebfoundation.org/legal/the-owf-1-0-agreements/owfa-1-0. TypeScript is a trademark of Microsoft Corporation. Table of Contents 1 Introduction ................................................................................................................................................................................... 1 1.1 Ambient Declarations ..................................................................................................................................................... 3 1.2 Function Types .................................................................................................................................................................. 3 1.3 Object Types ...................................................................................................................................................................... 4 1.4 Structural Subtyping ....................................................................................................................................................... 6 1.5 Contextual Typing ............................................................................................................................................................ 7 1.6 Classes .................................................................................................................................................................................
    [Show full text]
  • Scala Tutorial
    Scala Tutorial SCALA TUTORIAL Simply Easy Learning by tutorialspoint.com tutorialspoint.com i ABOUT THE TUTORIAL Scala Tutorial Scala is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way. Scala has been created by Martin Odersky and he released the first version in 2003. Scala smoothly integrates features of object-oriented and functional languages. This tutorial gives a great understanding on Scala. Audience This tutorial has been prepared for the beginners to help them understand programming Language Scala in simple and easy steps. After completing this tutorial, you will find yourself at a moderate level of expertise in using Scala from where you can take yourself to next levels. Prerequisites Scala Programming is based on Java, so if you are aware of Java syntax, then it's pretty easy to learn Scala. Further if you do not have expertise in Java but you know any other programming language like C, C++ or Python, then it will also help in grasping Scala concepts very quickly. Copyright & Disclaimer Notice All the content and graphics on this tutorial are the property of tutorialspoint.com. Any content from tutorialspoint.com or this tutorial may not be redistributed or reproduced in any way, shape, or form without the written permission of tutorialspoint.com. Failure to do so is a violation of copyright laws. This tutorial may contain inaccuracies or errors and tutorialspoint provides no guarantee regarding the accuracy of the site or its contents including this tutorial. If you discover that the tutorialspoint.com site or this tutorial content contains some errors, please contact us at [email protected] TUTORIALS POINT Simply Easy Learning Table of Content Scala Tutorial ..........................................................................
    [Show full text]
  • Smalltalk Smalltalk
    3/8/2008 CSE 3302 Programming Languages Smalltalk Everyygthing is obj ect. Obj ects communicate by messages. Chengkai Li Spring 2008 Lecture 14 – Smalltalk, Spring Lecture 14 – Smalltalk, Spring CSE3302 Programming Languages, UT-Arlington 1 CSE3302 Programming Languages, UT-Arlington 2 2008 ©Chengkai Li, 2008 2008 ©Chengkai Li, 2008 Object Hierarchy Object UndefinedObject Boolean Magnitude Collection No Data Type. True False Set … There is only Class. Char Number … Fraction Integer Float Lecture 14 – Smalltalk, Spring Lecture 14 – Smalltalk, Spring CSE3302 Programming Languages, UT-Arlington 3 CSE3302 Programming Languages, UT-Arlington 4 2008 ©Chengkai Li, 2008 2008 ©Chengkai Li, 2008 Syntax • Smalltalk is really “small” – Only 6 keywords (pseudo variables) – Class, object, variable, method names are self explanatory Sma llta lk Syn tax is Simp le. – Only syntax for calling method (messages) and defining method. • No syntax for control structure • No syntax for creating class Lecture 14 – Smalltalk, Spring Lecture 14 – Smalltalk, Spring CSE3302 Programming Languages, UT-Arlington 5 CSE3302 Programming Languages, UT-Arlington 6 2008 ©Chengkai Li, 2008 2008 ©Chengkai Li, 2008 1 3/8/2008 Expressions Literals • Literals • Number: 3 3.5 • Character: $a • Pseudo Variables • String: ‘ ’ (‘Hel’,’lo!’ and ‘Hello!’ are two objects) • Symbol: # (#foo and #foo are the same object) • Variables • Compile-time (literal) array: #(1 $a 1+2) • Assignments • Run-time (dynamic) array: {1. $a. 1+2} • Comment: “This is a comment.” • Blocks • Messages Lecture 14 – Smalltalk, Spring Lecture 14 – Smalltalk, Spring CSE3302 Programming Languages, UT-Arlington 7 CSE3302 Programming Languages, UT-Arlington 8 2008 ©Chengkai Li, 2008 2008 ©Chengkai Li, 2008 Pseudo Variables Variables • Instance variables.
    [Show full text]
  • Python Functions
    PPYYTTHHOONN FFUUNNCCTTIIOONNSS http://www.tutorialspoint.com/python/python_functions.htm Copyright © tutorialspoint.com A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. As you already know, Python gives you many built-in functions like print, etc. but you can also create your own functions. These functions are called user-defined functions. Defining a Function You can define functions to provide the required functionality. Here are simple rules to define a function in Python. Function blocks begin with the keyword def followed by the function name and parentheses ( ). Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses. The first statement of a function can be an optional statement - the documentation string of the function or docstring. The code block within every function starts with a colon : and is indented. The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None. Syntax def functionname( parameters ): "function_docstring" function_suite return [expression] By default, parameters have a positional behavior and you need to inform them in the same order that they were defined. Example The following function takes a string as input parameter and prints it on standard screen. def printme( str ): "This prints a passed string into this function" print str return Calling a Function Defining a function only gives it a name, specifies the parameters that are to be included in the function and structures the blocks of code.
    [Show full text]
  • From Perl to Python
    From Perl to Python Fernando Pineda 140.636 Oct. 11, 2017 version 0.1 3. Strong/Weak Dynamic typing The notion of strong and weak typing is a little murky, but I will provide some examples that provide insight most. Strong vs Weak typing To be strongly typed means that the type of data that a variable can hold is fixed and cannot be changed. To be weakly typed means that a variable can hold different types of data, e.g. at one point in the code it might hold an int at another point in the code it might hold a float . Static vs Dynamic typing To be statically typed means that the type of a variable is determined at compile time . Type checking is done by the compiler prior to execution of any code. To be dynamically typed means that the type of variable is determined at run-time. Type checking (if there is any) is done when the statement is executed. C is a strongly and statically language. float x; int y; # you can define your own types with the typedef statement typedef mytype int; mytype z; typedef struct Books { int book_id; char book_name[256] } Perl is a weakly and dynamically typed language. The type of a variable is set when it's value is first set Type checking is performed at run-time. Here is an example from stackoverflow.com that shows how the type of a variable is set to 'integer' at run-time (hence dynamically typed). $value is subsequently cast back and forth between string and a numeric types (hence weakly typed).
    [Show full text]
  • Declare New Function Javascript
    Declare New Function Javascript Piggy or embowed, Levon never stalemating any punctuality! Bipartite Amory wets no blackcurrants flagged anes after Hercules supinate methodically, quite aspirant. Estival Stanleigh bettings, his perspicaciousness exfoliating sopped enforcedly. How a javascript objects for mistakes to retain the closure syntax and maintainability of course, written by reading our customers and line? Everything looks very useful. These values or at first things without warranty that which to declare new function javascript? You declare a new class and news to a function expressions? Explore an implementation defined in new row with a function has a gas range. If it allows you probably work, regular expression evaluation but mostly warszawa, and to retain the explanation of. Reimagine your namespaces alone relate to declare new function javascript objects for arrow functions should be governed by programmers avoid purity. Js library in the different product topic and zip archives are. Why is selected, and declare a superclass method decorators need them into functions defined by allocating local time. It makes more sense to handle work in which support optional, only people want to preserve type to be very short term, but easier to! String type variable side effects and declarations take a more situations than or leading white list of merchantability or a way as explicit. You declare many types to prevent any ecmascript program is not have two categories by any of parameters the ecmascript is one argument we expect. It often derived from the new knowledge within the string, news and error if the function expression that their prototype.
    [Show full text]
  • An Overview of the Scala Programming Language
    An Overview of the Scala Programming Language Second Edition Martin Odersky, Philippe Altherr, Vincent Cremet, Iulian Dragos Gilles Dubochet, Burak Emir, Sean McDirmid, Stéphane Micheloud, Nikolay Mihaylov, Michel Schinz, Erik Stenman, Lex Spoon, Matthias Zenger École Polytechnique Fédérale de Lausanne (EPFL) 1015 Lausanne, Switzerland Technical Report LAMP-REPORT-2006-001 Abstract guage for component software needs to be scalable in the sense that the same concepts can describe small as well as Scala fuses object-oriented and functional programming in large parts. Therefore, we concentrate on mechanisms for a statically typed programming language. It is aimed at the abstraction, composition, and decomposition rather than construction of components and component systems. This adding a large set of primitives which might be useful for paper gives an overview of the Scala language for readers components at some level of scale, but not at other lev- who are familar with programming methods and program- els. Second, we postulate that scalable support for compo- ming language design. nents can be provided by a programming language which unies and generalizes object-oriented and functional pro- gramming. For statically typed languages, of which Scala 1 Introduction is an instance, these two paradigms were up to now largely separate. True component systems have been an elusive goal of the To validate our hypotheses, Scala needs to be applied software industry. Ideally, software should be assembled in the design of components and component systems. Only from libraries of pre-written components, just as hardware is serious application by a user community can tell whether the assembled from pre-fabricated chips.
    [Show full text]
  • Scala Is an Object Functional Programming and Scripting Language for General Software Applications Designed to Express Solutions in a Concise Manner
    https://www.guru99.com/ ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 1) Explain what is Scala? Scala is an object functional programming and scripting language for general software applications designed to express solutions in a concise manner. 2) What is a ‘Scala set’? What are methods through which operation sets are expressed? Scala set is a collection of pairwise elements of the same type. Scala set does not contain any duplicate elements. There are two kinds of sets, mutable and immutable. 3) What is a ‘Scala map’? Scala map is a collection of key or value pairs. Based on its key any value can be retrieved. Values are not unique but keys are unique in the Map. 4) What is the advantage of Scala? • Less error prone functional style • High maintainability and productivity • High scalability • High testability • Provides features of concurrent programming 5) In what ways Scala is better than other programming language? • The arrays uses regular generics, while in other language, generics are bolted on as an afterthought and are completely separate but have overlapping behaviours with arrays. • Scala has immutable “val” as a first class language feature. The “val” of scala is similar to Java final variables. Contents may mutate but top reference is immutable. • Scala lets ‘if blocks’, ‘for-yield loops’, and ‘code’ in braces to return a value. It is more preferable, and eliminates the need for a separate ternary
    [Show full text]
  • Scala by Example (2009)
    Scala By Example DRAFT January 13, 2009 Martin Odersky PROGRAMMING METHODS LABORATORY EPFL SWITZERLAND Contents 1 Introduction1 2 A First Example3 3 Programming with Actors and Messages7 4 Expressions and Simple Functions 11 4.1 Expressions And Simple Functions...................... 11 4.2 Parameters.................................... 12 4.3 Conditional Expressions............................ 15 4.4 Example: Square Roots by Newton’s Method................ 15 4.5 Nested Functions................................ 16 4.6 Tail Recursion.................................. 18 5 First-Class Functions 21 5.1 Anonymous Functions............................. 22 5.2 Currying..................................... 23 5.3 Example: Finding Fixed Points of Functions................ 25 5.4 Summary..................................... 28 5.5 Language Elements Seen So Far....................... 28 6 Classes and Objects 31 7 Case Classes and Pattern Matching 43 7.1 Case Classes and Case Objects........................ 46 7.2 Pattern Matching................................ 47 8 Generic Types and Methods 51 8.1 Type Parameter Bounds............................ 53 8.2 Variance Annotations.............................. 56 iv CONTENTS 8.3 Lower Bounds.................................. 58 8.4 Least Types.................................... 58 8.5 Tuples....................................... 60 8.6 Functions.................................... 61 9 Lists 63 9.1 Using Lists.................................... 63 9.2 Definition of class List I: First Order Methods..............
    [Show full text]
  • Functional Programming for Imperative Programmers
    Functional Programming for Imperative Programmers R. Sekar This document introduces functional programming for those that are used to imperative languages, but are trying to come to terms with recursion and other techniques used in functional programming. We use OCaml as the primary language, and we assume that the reader has been introduced to its basic syntax and features. The goal of this document is to help these programmers get more comfortable with functional programming techniques, while addressing the following topics: • Understanding and visualizing recursion • Iteration as a special case of recursion { Imperative programming in functional languages by \threading" state through functions • Higher-order functions and iteration • Writing efficient functional code • Functional programming in imperative languages 1 Simple Vs Mutual Recursion Recursion can be simple recursion, which means that a function f is recursive with itself. In other words, f is defined in terms of f and h1; : : : ; hn, where h1; : : : ; hn have no dependence on f. In OCaml, such a function f can be defined using a single let rec. The factorial function defined below is one such example: let rec fact n = i f n=0 then 1 else n ∗ ( fact ( n−1)) In this case, fact is defined in terms of itself and two other functions, if and the subtraction function on integers. As a second example, consider the Fibonacci function, where each invocation of fib makes two recursive invoca- tions of fib. let rec fib n = i f n=0 then 0 else i f n=1 then 1 else ( fib ( n−1)) + ( fib ( n−2)) In a more complex case of recursion, functions can be mutually recursive, i.e., f is defined in terms of another function g, which is in turn defined in terms of f.
    [Show full text]
  • Lambda Expressions
    Back to Basics Lambda Expressions Barbara Geller & Ansel Sermersheim CppCon September 2020 Introduction ● Prologue ● History ● Function Pointer ● Function Object ● Definition of a Lambda Expression ● Capture Clause ● Generalized Capture ● This ● Full Syntax as of C++20 ● What is the Big Deal ● Generic Lambda 2 Prologue ● Credentials ○ every library and application is open source ○ development using cutting edge C++ technology ○ source code hosted on github ○ prebuilt binaries are available on our download site ○ all documentation is generated by DoxyPress ○ youtube channel with over 50 videos ○ frequent speakers at multiple conferences ■ CppCon, CppNow, emBO++, MeetingC++, code::dive ○ numerous presentations for C++ user groups ■ United States, Germany, Netherlands, England 3 Prologue ● Maintainers and Co-Founders ○ CopperSpice ■ cross platform C++ libraries ○ DoxyPress ■ documentation generator for C++ and other languages ○ CsString ■ support for UTF-8 and UTF-16, extensible to other encodings ○ CsSignal ■ thread aware signal / slot library ○ CsLibGuarded ■ library for managing access to data shared between threads 4 Lambda Expressions ● History ○ lambda calculus is a branch of mathematics ■ introduced in the 1930’s to prove if “something” can be solved ■ used to construct a model where all functions are anonymous ■ some of the first items lambda calculus was used to address ● if a sequence of steps can be defined which solves a problem, then can a program be written which implements the steps ○ yes, always ● can any computer hardware
    [Show full text]