Functional Programming in C++11

Similar documents
Functional Programming

Massachusetts Institute of Technology 6.005: Elements of Software Construction Fall 2011 Quiz 2 November 21, 2011 SOLUTIONS.

Answers to Review Questions Chapter 7

CSc 372. Comparative Programming Languages. 21 : Haskell Accumulative Recursion. Department of Computer Science University of Arizona

C++ INTERVIEW QUESTIONS

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Chapter 15 Functional Programming Languages

ML for the Working Programmer

Chapter 7: Functional Programming Languages

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

TOWARDS A GREEN PROGRAMMING PARADIGM FOR MOBILE SOFTWARE DEVELOPMENT

UNIVERSITY OF LONDON (University College London) M.Sc. DEGREE 1998 COMPUTER SCIENCE D16: FUNCTIONAL PROGRAMMING. Answer THREE Questions.

Recursion. Slides. Programming in C++ Computer Science Dept Va Tech Aug., Barnette ND, McQuain WD

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Sample CSE8A midterm Multiple Choice (circle one)

sqlpp11 - An SQL Library Worthy of Modern C++

CSI33 Data Structures

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Goals for This Lecture:

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Curriculum Map. Discipline: Computer Science Course: C++

CISC 181 Project 3 Designing Classes for Bank Accounts

Sample Questions Csci 1112 A. Bellaachia

Programming Language Features (cont.) CMSC 330: Organization of Programming Languages. Parameter Passing in OCaml. Call-by-Value

Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

[Refer Slide Time: 05:10]

Example. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification:

The Needle Programming Language

Moving from CS 61A Scheme to CS 61B Java

Functional Programming. Functional Programming Languages. Chapter 14. Introduction

Object Oriented Software Design II

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

IRA EXAMPLES. This topic has two examples showing the calculation of the future value an IRA (Individual Retirement Account).

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

CS 241 Data Organization Coding Standards

C++ Programming Language

C++FA 3.1 OPTIMIZING C++

C++FA 5.1 PRACTICE MID-TERM EXAM

Programming Languages CIS 443

Output: struct treenode{ int data; struct treenode *left, *right; } struct treenode *tree_ptr;

Chapter 2: Elements of Java

Conversion of Measurement Data from MDF to ATFX

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

What Is Recursion? Recursion. Binary search example postponed to end of lecture

by Mario Fusco Monadic

Programming Languages in Artificial Intelligence

N3458: Simple Database Integration in C++11

The While Loop. Objectives. Textbook. WHILE Loops

Konzepte objektorientierter Programmierung

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

Chapter 5. Selection 5-1

16. Recursion. COMP 110 Prasun Dewan 1. Developing a Recursive Solution

Moving from C++ to VBA

Big Data Analytics. Lucas Rego Drumond

Channel Access Client Programming. Andrew Johnson Computer Scientist, AES-SSG

Compilation 2012 Domain-Specific Languages and Syntax Extensions

recursion here it is in C++ power function cis15 advanced programming techniques, using c++ fall 2007 lecture # VI.1

An Incomplete C++ Primer. University of Wyoming MA 5310

The Clean programming language. Group 25, Jingui Li, Daren Tuzi

Schedule. Structures and Classes in C++ Outline. Goals for This Topic. Another Example of a Structure. What is a Structure? Classes May 12-17, 2005

Programming with Arrows

Chapter 5 Functions. Introducing Functions

CORBA Programming with TAOX11. The C++11 CORBA Implementation

Recursion. Definition: o A procedure or function that calls itself, directly or indirectly, is said to be recursive.

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

Lecture 11: Tail Recursion; Continuations

Busy Java Developer's Guide to Functional Programming. Ted Neward Neward & Associates

The countdown problem

Solving Problems Recursively

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Bevezetés a C++ Standard Template Library-be

Semester Review. CSC 301, Fall 2015

Programming Database lectures for mathema

Detecting Pattern-Match Failures in Haskell. Neil Mitchell and Colin Runciman York University

Common Data Structures

4.2 Sorting and Searching

Class 16: Function Parameters and Polymorphism

Python Lists and Loops

Variable Base Interface

Regression Verification: Status Report

Ch 7-1. Object-Oriented Programming and Classes

CS177 MIDTERM 2 PRACTICE EXAM SOLUTION. Name: Student ID:

Compositional hardware virtualization. Raphael kena Poss University of Amsterdam January 11th, 2014

6. Control Structures

Member Functions of the istream Class

Section 6 Spring 2013

Conditions & Boolean Expressions

CSE 373: Data Structure & Algorithms Lecture 25: Programming Languages. Nicki Dell Spring 2014

Syntax Check of Embedded SQL in C++ with Proto

For the next three questions, consider the class declaration: Member function implementations put inline to save space.

Compiler Construction

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Overview. Elements of Programming Languages. Advanced constructs. Motivating inner class example

Binary storage of graphs and related data

Passing 1D arrays to functions.

Binary Multiplication

Transcription:

Functional Programming in C++11 science + computing ag IT-Dienstleistungen und Software für anspruchsvolle Rechnernetze Tübingen München Berlin Düsseldorf

An Overview Programming in a functional style Why functional programming? What is functional programming? Characteristics of functional programming first-class functions higher-order functions pure functions recursion list processing lazy evaluation What's missing? Seite 2

Programming in a functional style Automatic type deduction with auto and decltype Support for lambda-functions closures functions as data Partial function application std::function and std::bind lambda-functions and auto Higher-order functions in the algorithms of the STL List manipulation with variadic templates Pattern matching with full and partial template specialisation Lazy evaluation with std::async Constrained templates (concepts) will be part of C++1y. Seite 3

Why functional programming? Standard Template Library (STL) more effective use with lambda-functions accumulate(vec.begin(),vec.end(), [](int a,int b){return a+b;}); Template Programming recognizing functional patterns template <int N> struct Fac{ static int const val= N * Fac<N-1>::val; }; template <> struct Fac<0>{ static int const val= 1; }; Better programming style reasoning about side effects more concise for (auto v: vec) cout << v << " " << endl; Seite 4

What is functional programming? Functional programming is programming with mathematical functions. Mathematical functions are functions that each time return the same value when given the same arguments (referencial transparency). Functions are not allowed to have side effects. The function invocation can be replaced by the result. The optimizer is allowed to rearrange the function invocations or he can perform the function invocation on a different thread. The program flow will be driven by the data dependencies and not by the sequence of instructions. Seite 5

Characteristics of functional programming Seite 6

First-class functions First-class functions are firstclass citizens. Functions are like data. Functions can be passed as arguments to other functions. can be returned from other functions. can be assigned to variables or stored in a data structure. Seite 7

First-class functions: dispatch table map<const char,function<double(double,double)>> tab; tab.insert(make_pair('+',[](double a,double b){return a + b;})); tab.insert(make_pair('-',[](double a,double b){return a - b;})); tab.insert(make_pair('*',[](double a,double b){return a * b;})); tab.insert(make_pair('/',[](double a,double b){return a / b;})); cout << "3.5+4.5= " << tab['+'](3.5,4.5) << endl; // 8 cout << "3.5*4.5= " << tab['*'](3.5,4.5) << endl; // 15.75 tab.insert(make_pair('^', [](double a,double b){return pow(a,b);})); cout << "3.5^4.5= " << tab['^'](3.5,4.5) << endl; // 280.741 Seite 8

Higher-order functions Higher-order functions are functions that accept other functions as argument or return them as result. The three classics: map: Apply a function to each element of a list. filter: Remove elements from a list. fold: (source: http://musicantic.blogspot.de, 2012-10-16) Reduce a list to a single value by successively applying a binary operation. Seite 9

Higher-order functions Each programming language supporting programming in a functional style offers map, filter and fold. Haskell Python C++ map map std::transform filter filter std::remove_if fold* reduce std::accumulate map, filter and fold are 3 powerful functions which are applicable in many cases. map + reduce= MapReduce Seite 10

Higher-order functions Lists and vectors: Haskell: vec= [1.. 9] str= ["Programming","in","a","functional","style."] Python: vec=range(1,10) str=["programming","in","a","functional","style."] C++11: vector<int> vec{1,2,3,4,5,6,7,8,9} vector<string>str{"programming","in","a","functional", "style."} The results will be displayed in Haskell or Python notation. Seite 11

Higher-order functions map Haskell: map(\a a^2) vec map(\a -> length a) str Python: map(lambda x : x*x, vec) map(lambda x : len(x),str) C++11: transform(vec.begin(),vec.end(),vec.begin(), [](int i){ return i*i; }); transform(str.begin(),str.end(),back_inserter(vec2), [](string s){ return s.length(); }); Results: [1,4,9,16,25,36,49,64,81] [11,2,1,10,6] Seite 12

Higher-order functions filter Haskell: filter(\x-> x<3 x>8) vec filter(\x isupper(head x)) str Python: filter(lambda x: x<3 or x>8, vec) filter(lambda x: x[0].isupper(),str) C++11: auto it= remove_if(vec.begin(),vec.end(), [](int i){ return!((i < 3) or (i > 8)) }); auto it2= remove_if(str.begin(),str.end(), [](string s){ return!(isupper(s[0])); }); Results: [1,2,9] and [ Programming ] Seite 13

Higher-order functions fold Haskell: foldl (\a b a * b) 1 vec foldl (\a b a ++ ":" ++ b ) "" str Python: reduce(lambda a, b: a * b, vec, 1) reduce(lambda a, b: a + b, str,"") C++11: accumulate(vec.begin(),vec.end(),1, [](int a, int b){ return a*b; }); accumulate(str.begin(),str.end(),string(""), [](string a,string b){ return a+":"+b; }); Results: 362800 and :Programming:in:a:functional:style. Seite 14

Pure functions Pure versus impure functions (from the book Real World Haskell) pure functions Always produces the same result when given the same parameters. Never have side effects. Never alter state. impure functions May produce different results for the same parameters. May have side effects. May alter the global state of the program, system, or world. Pure functions are isolated. The program is easier to Seite 15 reason about. refactor and test. Great opportunity for optimization Saving results of pure function invocations Reordering pure function invocations or performing them on other threads

Pure functions Monads are the Haskell solution to deal with the impure world. A Monad encapsulates the impure world in pure Haskell. is a imperative subsystem in Haskell. is a structure which represents computation. has to define the composition of computations. Examples: I/O monad for dealing with input and output Maybe monad for computations that can fail List monad for computations with zero or more valid answers State monad for representing stateful computation STM monad for software transactional memory Seite 16

Recursion Seite 17 Loops: Recursion is the control structure. A loop (for int i=0; i <= 0; ++i) needs a variable i. Mutable variables are not known in functional languages like Haskell. Recursion combined with list processing is a powerful pattern in functional languages.

Recursion Haskell: fac 0= 1 fac n= n * fac (n-1) C++: template<int N> struct Fac{ static int const value= N * Fac<N-1>::value; }; template <> struct Fac<0>{ static int const value = 1; }; Result: fac(5) == Fac<5>::value == 120 Seite 18

List processing LISt Processing is the characteristic for functional programming: transforming a list into another list reducing a list to a value The functional pattern for list processing: 1)Processing the head (x) of the list 2)Recursively processing the tail (xs) of the list => Go to step 1). Examples: mysum [] = 0 mysum (x:xs) = x + mysum xs mysum [1,2,3,4,5] // 15 mymap f [] = [] mymap f (x:xs)= f x: mymap f xs mymap (\x x*x)[1,2,3] // [1,4,9] Seite 19

List processing template<int...> struct mysum; template<>struct mysum<>{ static const int value= 0; }; template<int i, int... tail> struct mysum<i,tail...>{ static const int value= i + mysum<tail...>::value; }; int sum= mysum<1,2,3,4,5>::value; // sum == 15 You do not really want to implement mymap with variadic templates. (http://www.linux-magazin.de/heft-abo/ausgaben/2011/01/c/%28offset%29/2) Seite 20

List processing The key idea behind list processing is pattern matching. First match in Haskell Seite 21 mult n 0 = 0 mult n 1 = n mult n m = (mult n (m 1)) + n Example: mult 3 2 = (mult 3 (2 1)) + 3 = (mult 3 1 ) + 3 = 3 + 3 = 6 Best match in C++11 template < int N1, int N2 > class Mult { }; template < int N1 > class Mult <N1,1> { }; template < int N1 > class Mult <N1,0> { };

Lazy Evaluation Lazy evaluation (non-strict evaluation) evaluates the expression only if needed. Haskell is lazy, as the following works length [2+1, 3*2, 1/0, 5-4] C++ is eager, but the following works template <typename... Args> void mysize(args... args) { } Advantages: cout << sizeof...(args) << endl; mysize("rainer",1/0); Saving time and memory usage Working with infinite data structures Seite 22

Lazy Evaluation Examples: successor i= i: (successor (i+1)) take 5 ( successor 10 ) // [10,11,12,13,14] odds= takewhile (< 1000). filter odd. map (^2) [1..]= [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15... Control -C odds [1..] // [1,9,25,, 841,961] Special case: short circuit evaluation if ( true or (1/0) )cout << "short circuit evaluation in C++\n"; Seite 23

What's missing? List comprehension: Syntactic sugar of the sweetest kind with map and filter Examples: [(s,len(s)) for s in ["Only","for"]] # [('Only', 4), ('for', 3)] [i*i for i in range(11) if i%2 == 0] # [0,4,16,36,64,100] Function composition: Programming with LEGO bricks Examples: (reverse. sort)[10,2,8,1,9,5,3,6,4,7]- - [10,9,8,7,6,5,4,3,2,1] Seite 24 thelongesttitle= head. reverse. sortby(comparing length). filter istitle thelongesttitle words("a Sentence Full Of Titles.") Result: "Sentence"

Functional Programming in C++11 Vielen Dank für Ihre Aufmerksamkeit. Rainer Grimm science + computing ag www.science-computing.de phone +49 7071 9457-253 r.grimm@science-computing.de