A program is a sequence of instructions that are run by the processor. To run a program, it must be compiled into binary code and given to the operating system. The OS then gives the code to the processor to execute. Functions allow code to be reused by defining operations and optionally returning values. Strings are sequences of characters that can be manipulated using indexes and methods. Common string methods include upper() and concatenation using +.
Introduction to functional programming (In Arabic)Omar Abdelhafith
Functional programming is a declarative programming paradigm where programs are built around mathematical functions and immutable data transformation (1). Key aspects include using pure functions that always return the same output for the same input and avoid side effects, immutable data that does not change state, representing everything as expressions rather than statements, and treating functions as data that can be passed into other functions or returned from them (2). These characteristics allow functional programs to be deterministic, avoid bugs from mutable state, and more easily write parallel and distributed programs (3).
The document outlines Java 8's Stream API. It discusses stream building blocks like default methods, functional interfaces, lambda expressions, and method references. It describes characteristics of streams like laziness and parallelization. It covers creating streams from collections, common functional interfaces, and the anatomy of a stream pipeline including intermediate and terminal operations. It provides examples of common stream API methods like forEach, map, filter, findFirst, toArray, collect, and reduce.
F# is a functional programming language that can also support imperative programming. It compiles to .NET code and allows interoperability with other .NET languages. Some key features include type inference, pattern matching, immutable data structures, and support for functions as first-class values. The presentation provides examples of common F# concepts like recursion, tuples, lists, objects, and using F# for GUI programming with WinForms.
The document provides an introduction and tutorial to the Python programming language. It covers 13 chapters that introduce very basic Python concepts up to more advanced topics like classes and CGI programming. The chapters include variables, data types, operators, conditionals, functions, iteration, strings, collection data types, exception handling, modules, files, documentation, and classes. The document also notes several sources that were used to create the tutorial and provides example code snippets throughout to demonstrate the concepts discussed.
- The document discusses concurrent and parallel programming in Haskell, including the use of threads, MVars, and software transactional memory (STM).
- STM provides atomic execution of blocks of code, allowing failed transactions to automatically retry without race conditions or data corruption.
- Strategies can be used to evaluate expressions in parallel using different evaluation models like head normal form or weak head normal form.
- While functional programs may seem to have inherent parallelism, in practice extracting parallelism can be difficult due to data dependencies and irregular patterns of computation.
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Edureka!
** Python Certification Training: https://www.edureka.co/python **
This Edureka PPT on Python Functions tutorial covers all the important aspects of functions in Python right from the introduction to what functions are, all the way till checking out the major functions and using the code-first approach to understand them better.
Agenda
Why use Functions?
What are the Functions?
Types of Python Functions
Built-in Functions in Python
User-defined Functions in Python
Python Lambda Function
Conclusion
Python Tutorial Playlist: https://goo.gl/WsBpKe
Blog Series: http://bit.ly/2sqmP4s
Follow us to never miss an update in the future.
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
Presented on 27th September 2017 to a joint meeting of 'Cork Functional Programmers' and the 'Cork Java Users Group'
Based on the Kotlin Language programming course from Instil. For more details see https://instil.co/courses/kotlin-development/
Regular expressions are a powerful tool for searching, matching, and parsing text patterns. They allow complex text patterns to be matched with a standardized syntax. All modern programming languages include regular expression libraries. Regular expressions can be used to search strings, replace parts of strings, split strings, and find all occurrences of a pattern in a string. They are useful for tasks like validating formats, parsing text, and finding/replacing text. This document provides examples of common regular expression patterns and methods for using regular expressions in Python.
This file contains the first steps any beginner can take as he/she starts a journey into the rich and beautiful world of Python programming. From basics such as variables to data types and recursions, this document touches briefly on these concepts. It is not, by any means, an exhaustive guide to learn Python, but it serves as a good starting point and motivation.
Python is a versatile, object-oriented programming language that can be used for web development, data analysis, and more. It has a simple syntax and is easy to read and learn. Key features include being interpreted, dynamically typed, supporting functional and object-oriented programming. Common data types include numbers, strings, lists, dictionaries, tuples, and files. Functions and classes can be defined to organize and reuse code. Regular expressions provide powerful string manipulation. Python has a large standard library and is used widely in areas like GUIs, web scripting, AI, and scientific computing.
Functional Python Webinar from October 22nd, 2014Reuven Lerner
Slides from my free functional Python webinar, given on October 22nd, 2014. Discussion included functional programming as a perspective, passing functions as data, and writing programs that take functions as parameters. Includes (at the end) a coupon for my new ebook, Practice Makes Python.
This document provides a summary of MATLAB commands and their equivalents in numerical Python (NumPy) and R. It covers topics such as help, operators, vectors, matrices, random number generation and more. The goal is to provide a quick reference for switching between MATLAB, Python, Scilab, Octave, Gnuplot and R for numeric processing and data visualization. Equivalents are given for each MATLAB command or function in the other languages.
Using functional concepts in Python. Introduction to functional programming and exploring each of the concepts, like map, filter and reduce in detail and how functional programming can help creating massively parallel software systems
What is functional programming? This talk sets out to demystify the functional programming paradigm, debunk common myths, and reveal examples of why FP is advantageous compared to imperative programming.
This document provides a cheat sheet for Python basics. It begins with an introduction to Python and its advantages. It then covers key Python data types like strings, integers, floats, lists, tuples, and dictionaries. It explains how to define variables, functions, conditional statements, and loops. The document also demonstrates built-in functions, methods for manipulating common data structures, and other Python programming concepts in a concise and easy to understand manner.
This document provides an overview and introduction to key Python packages for scientific computing and data science. It discusses Jupyter notebooks for interactive coding and visualization, NumPy for N-dimensional arrays and math operations, SciPy for scientific computing functions, matplotlib for plotting, and pandas for working with labeled data structures. The document emphasizes that NumPy provides foundational N-dimensional arrays, SciPy builds on this with additional mathematical and scientific routines, and matplotlib and pandas complement these with visualization and labeled data functionality.
This document provides an introduction to the Python programming language. It covers Python's background, syntax, types, operators, control flow, functions, classes, tools, and IDEs. Key points include that Python is a multi-purpose, object-oriented language that is interpreted, strongly and dynamically typed. It focuses on readability and has a huge library of modules. Popular Python IDEs include Emacs, Vim, Komodo, PyCharm, and Eclipse.
Functions in C++ provide more capabilities than functions in C, including function prototypes, function overloading, default arguments, and operator overloading. Function prototypes allow strong type checking and prevent illegal values from being passed to functions. Function overloading allows multiple functions to have the same name if they have different parameters. Default arguments allow functions to be called without passing all parameters by using default values defined in the function prototype. Operator overloading extends operators like + and - to non-standard data types like strings. Inline functions help reduce function call overhead by inserting the function code directly in the calling code.
I am Leonard K. I am a C++ Homework Expert at cpphomeworkhelp.com. I hold a Masters in Programming from the University of Arkansas, USA. I have been helping students with their homework for the past 9 years. I solve homework related to C++.
Visit cpphomeworkhelp.com or email info@cpphomeworkhelp.com. You can also call on +1 678 648 4277 for any assistance with C++ Homework.
A talk from CppEurope 2019 about functional programming in C++.
It talks about lambdas, immutability, operations with functions (partial application, currying, functional composition), shows an example and ends with a procedure for refactoring legacy code.
C++ is an object-oriented programming language created by Bjarne Stroustrup in 1985 that maintains aspects of C while adding object-oriented features like classes. C++ can be used to create everything from small programs to large applications and is a powerful general-purpose language. Inheritance allows code reusability by creating new classes from existing classes or base classes, where derived classes inherit capabilities from base classes but can add their own features and refinements. Polymorphism enables objects to react differently to the same function call through virtual functions, allowing different classes that inherit from a base class to provide their own implementation of a function.
Porque aprender haskell me fez um programador python melhor?UFPA
The document discusses how learning Haskell made the author a better Python programmer. It argues that by learning Haskell, the author was able to better understand Python code, code written by others, the Python language itself, and frameworks built for Python. Learning Haskell provided a deeper understanding of programming languages in general and allowed the author to critically evaluate their own language choices.
This document provides an outline and overview of functions in C++. It discusses:
- The definition of a function as a block of code that performs a specific task and can be called from other parts of the program.
- The standard library that is included in C++ and provides useful tools like containers, iterators, algorithms and more.
- The parts of a function definition including the return type, name, parameters, and body.
- How to declare functions, call functions by passing arguments, and how arguments are handled.
- Scope rules for local and global variables as they relate to functions.
The document discusses key concepts in C++ including:
1. The main() function is the entry point of a C++ program and can call other functions defined in the source code.
2. main() returns an int value to the operating system. Functions can also return values and references.
3. Functions help reduce code size, save memory, and improve readability and reusability. Parameters can be passed by value or reference.
4. Inline functions provide faster execution by inserting the function code directly into the calling function. They are best for short functions without loops.
A glimpse at some of the new features for the C++ programming languages that will be introduced by the upcoming C++17 Standard.
This talk was given at the Munich C++ User Group Meetup.
The use of the code analysis library OpenC++: modifications, improvements, er...PVS-Studio
The document discusses modifications and improvements made to the OpenC++ code analysis library. It describes 15 modifications to the library related to error corrections or adding new functionality. The modifications include adding support for new keywords, skipping compiler-specific keywords, getting values of numerical literals, and fixing file paths. The purpose is to help developers use and improve OpenC++, while also demonstrating how to modify the library code.
The document discusses functions in C programming. It defines functions as self-contained blocks of code that perform a specific task. Functions make a program modular and easier to debug. There are four main types of functions: functions with no arguments and no return value, functions with no arguments but a return value, functions with arguments but no return value, and functions with both arguments and a return value. Functions are called by their name and can pass data between the calling and called functions using arguments.
Twins: Object Oriented Programming and Functional ProgrammingRichardWarburton
Object-Oriented Programming has well established design principles, such as SOLID. For many developers architecture and functional programming are at odds with each other: they don’t know how their existing tricks of the trade convert into functional design. This problem becomes worse as hybrid languages such as Java 8 or Scala become common. We’ll talk about how functional programming helps you implement the SOLID principles, and how a functional mindset can actually help you achieve cleaner and simpler OO design.
This document provides an overview of C++ programming concepts including:
- Procedure-oriented programming focuses on tasks like reading, calculating and printing using functions, while object-oriented programming emphasizes data through objects and classes.
- Some problems with C include lack of consideration for data elements and lack of security for networks.
- C++ classes contain variables and functions to characterize objects. Data and functions are tied together and data is hidden.
- Key concepts explained include objects, member functions, constructors, destructors, inheritance and polymorphism.
- Examples demonstrate basic C++ programs, classes, objects, arrays of objects, function overloading and the this pointer.
Python is an interpreted, object-oriented programming language that uses indentation to identify blocks of code. It is dynamically typed and strongly typed, with objects determining types at runtime rather than requiring explicit type declaration. Common data types include mutable types like lists and dictionaries as well as immutable types like strings and tuples.
I am Joe L. I am a Programming Assignment Expert at programminghomeworkhelp.com. I hold a Ph.D. in Programming from, University of Chicago, USA. I have been helping students with their homework for the past 10 years. I solve assignments related to Programming.
Visit programminghomeworkhelp.com or email support@programminghomeworkhelp.com.You can also call on +1 678 648 4277 for any assistance with Programming Assignments.
This document discusses functions in C programming. It defines functions as blocks of code that perform specific tasks. It explains the key components of functions - function declaration, definition, and call. It provides examples of defining, declaring, and calling functions. It also discusses recursion, system-defined library functions, and user-defined functions.
This document summarizes a presentation about exploring SharePoint with the F# programming language. It discusses the history and characteristics of functional programming and F#, including that F# is a functional-first language developed by Microsoft Research. It also covers how to use the F# Client Object Model to connect to and query SharePoint, including loading references, creating a client context, and querying sites, lists, and list items. The presentation demonstrates iterating through lists and items and retrieving properties.
This document provides an overview of functional programming concepts. It discusses why functional programming is useful for building concurrent and thread-safe applications. Key concepts explained include immutable data, first class and higher order functions, lazy evaluation, pattern matching, monads, and monoids. Code examples are provided in JavaScript and Haskell to demonstrate functional programming techniques.
This document summarizes Lecture 1 of Real World Haskell. It introduces functional programming and Haskell, discusses the Haskell Platform and interactive interpreter ghci. It demonstrates defining simple functions and expressions, writing small interactive programs, and using recursion to number lines of text. Resources for learning more about Haskell are provided.
The document discusses Python interview questions and answers related to Python fundamentals like data types, variables, functions, objects and classes. Some key points include:
- Python is an interpreted, interactive and object-oriented programming language. It uses indentation to identify code blocks rather than brackets.
- Python supports dynamic typing where the type is determined at runtime. It is strongly typed meaning operations inappropriate for a type will fail with an exception.
- Common data types include lists (mutable), tuples (immutable), dictionaries, strings and numbers.
- Functions use def, parameters are passed by reference, and variables can be local or global scope.
- Classes use inheritance, polymorphism and encapsulation to create
This document discusses different types of functions in C++, including user-defined functions, library functions, function parameters, return values, function prototypes, and function overloading. It provides examples to illustrate key concepts like defining functions with different parameters and return types, passing arguments to functions, and returning values from functions. Storage classes like local, global, static local and register variables are also briefly covered. The document is an introduction to functions in C++ programming.
Existing methods for refactoring legacy code are either unsafe, or slow and require a lot of rare skills. I'm proposing a new method composed of three steps: refactor to pure functions, write tests for the pure functions, and refactor the pure functions to classes or something else. I believe that with a few mechanical steps a trained developer can safely refactor legacy code faster using this method.
The document discusses the author's experience with optional types in software design. It describes the author's shifting views on types over their career from enthusiast to professional to advocate for optional types. The author details how optional types can lead to cleaner, smaller code that is easier to change and requires fewer tests. Deep questions are also posed about the cognitive costs of abstractions, whether strong typing enables strong coupling, and how important names and contracts are in minimalist design. The conclusion is that minimalism exerts positive pressure on design through smaller code, better names, clear responsibilities and contracts, and clear tests.
This document discusses ways to raise the bar of software development by combining it with other disciplines. It proposes 6 intersections between software design and other fields: 1) Software Design and UX, 2) Other design disciplines, 3) Materials Science, 4) Math, 5) Engineering principles of built-in self-testing, and 6) Reaching out to scientists. It argues that considering ideas from other domains could improve software design and help address challenges like dependencies in legacy code. The document also suggests ways to fundamentally change development by precisely defining requirements and generating code from them.
What can we learn from other design disciplines? How do they learn design? What can we copy from them?
This is a challenge for software developers to start thinking as code designers, as people who use code as a material to prototype solutions to problems.
What is good software design? Why does it matter?
In this keynote, I addressed this complex problem. Going from the history of programming, through analogies with other design disciplines, ending with conclusions on what is good software design, and how to become a better designer.
Slides for a workshop on agile technical leadership.
Agile teams are complex adaptive systems. In order to obtain a certain level of consistency, required when you want effective teams, teams have to set constraints on themselves and to make strategic decisions. This workshop explores some of the constraints and the difficulties of making strategic technical decisions.
One of the difficulties of developers starting to apply Test Driven Development (TDD) is letting go of preconceived notions of design and allowing themselves to evolve it. I have successfully used TDD As If You Meant It as a way of showcasing how design grows when doing TDD. TDD As If You Meant It is a set of constraints created by Keith Braithwaite that forces developers to let go of their set blueprints and allow the design to evolve. I've noticed in code retreats and dojos that the technique is very difficult to get right. In this session, I will explain the core technique, the value of the technique and what I've learned by applying it and by helping others applying it.
How to identify, when to remove and how to remove a common pattern in code: duplication that can be refactored towards loops and more complex data structures. Also with code examples.
The document discusses removing structural duplication from code. It defines structural duplication as similar code structures that repeat even if the internal actions differ. Examples given include conditional statements, exception handling, and views. The risks of duplication include increased size and unintended changes. The document provides steps to remove duplication such as separating structure from actions, extracting data models, and using loops to consolidate duplicated code. Both advantages like improved separation of concerns and disadvantages like increased rigidity are discussed.
This document discusses continuous delivery and provides steps to achieve it. Continuous delivery aims to provide fast, high quality feedback at multiple levels through the development process. It recommends having automated source control, builds, testing, deployment, monitoring and self-healing systems. The key steps are to have automated builds that pass all tests with each change, to measure and improve code quality, to implement automated validation of both code and features through tests, and to deploy and monitor applications automatically to catch any issues. Containers can help developers deploy applications for testing more easily. The overall goal is to establish a pipeline that allows for frequent, low-risk deployments.
This document discusses why developers should use Docker containers. It notes that Docker can help solve problems with reproducibility across environments by packaging applications and dependencies into self-contained units. An example is provided of a Dockerfile for a Java Spark application that defines what is needed to build and run the application in a container. The document encourages asking questions and experimenting with Docker to take advantage of its benefits like ease of use, large community support, and speed.
As a programmer, you are wondering what it takes to grow your career in a fast-changing environment. This talk is about a path for your career growth.
As a manager you are wondering how you can optimize your software development teams. This talk is about a model to use for a rough evaluation and improvement of your teams.
As a business owner, CEO or CTO, your primary request for development teams is to quickly add features. This talk is about a model for optimizing implementation time.
The pyramid of programming skillsets is a model based on the usefulness of programming skills when changing code fast is the most important business objective. Let’s explore five skillset levels I identified when working with teams of programmers around Europe. We will discuss each level and how to move from one level to another.
We've been discussing software craftsmanship for years. But does it match the realities of a business? How?
This is a story about applying the ideas and practices of software craftsmanship for a real project in a difficult context. The conclusion? It helped us, it might help you as well.
How can you advance your career as a software developer? How can you assess your team as a team leader / technical lead / manager?
I created a simple model to answer these questions based upon the most common need in modern software applications: the need to add features fast.
All models are wrong, but some are useful. I found this model useful and I hope you will too.
The document summarizes 10 practices for staying focused as presented by Alexandru Bolboaca. The practices include value stream mapping to visualize workflow, using visual management boards to track progress, removing blockages, dealing with bottlenecks, ensuring adequate resources, maintaining staff flexibility, holding effective meetings, limiting interruptions, planning team learning, and improving overall workflow flow. The talk encourages focusing efforts to clarify vision, minimize distractions, and eliminate anything not adding value in order to better deliver products and services.
An introduction to Kanban I presented with Flavius Stef at the Bucharest Agile Meetup Group in February 2014. See the event details on http://www.meetup.com/The-Bucharest-Agile-Software-Meetup-Group/events/146222892/. See http://mozaicworks.com for articles and events about Kanban and agile
This talk answers questions asked about unit testing by attendees at ALE 2013.
It was created in two hours, starting from an open space session where we gathered the questions.
Incremental design means implementing solutions one usage example at a time by splitting problems into smaller subproblems and defining behaviors through examples. The incremental design process involves splitting problems to find increments, identifying behaviors through examples, implementing examples one by one, and refactoring the solution by minimizing similarities and simplifying. An example is discussed to illustrate applying test-driven development and behavior-driven development principles through proof-based design and thinking about the problem before the solution.
Exploring alternatives is part of the design process.
TDD is a way to do incremental design, or design while you write code.
So can we use TDD to explore design alternatives?
Turns out, I've seen a lot of design exploration during the 30+ code retreats I facilitated and attended. While I don't have a definite proof, it seems that TDD could be used for this purpose.
Software development... for all? (keynote at ICSOFT'2024)miso_uam
Our world runs on software. It governs all major aspects of our life. It is an enabler for research and innovation, and is critical for business competitivity. Traditional software engineering techniques have achieved high effectiveness, but still may fall short on delivering software at the accelerated pace and with the increasing quality that future scenarios will require.
To attack this issue, some software paradigms raise the automation of software development via higher levels of abstraction through domain-specific languages (e.g., in model-driven engineering) and empowering non-professional developers with the possibility to build their own software (e.g., in low-code development approaches). In a software-demanding world, this is an attractive possibility, and perhaps -- paraphrasing Andy Warhol -- "in the future, everyone will be a developer for 15 minutes". However, to make this possible, methods are required to tweak languages to their context of use (crucial given the diversity of backgrounds and purposes), and the assistance to developers throughout the development process (especially critical for non-professionals).
In this keynote talk at ICSOFT'2024 I presented enabling techniques for this vision, supporting the creation of families of domain-specific languages, their adaptation to the usage context; and the augmentation of low-code environments with assistants and recommender systems to guide developers (professional or not) in the development process.
A captivating AI chatbot PowerPoint presentation is made with a striking backdrop in order to attract a wider audience. Select this template featuring several AI chatbot visuals to boost audience engagement and spontaneity. With the aid of this multi-colored template, you may make a compelling presentation and get extra bonuses. To easily elucidate your ideas, choose a typeface with vibrant colors. You can include your data regarding utilizing the chatbot methodology to the remaining half of the template.
Major Outages in Major Enterprises Payara ConferenceTier1 app
In this session, we will be discussing major outages that happened in major enterprises. We will analyse the actual thread dumps, heap dumps, GC logs, and other artifacts captured at the time of the problem. After this session, troubleshooting CPU spikes, OutOfMemoryError, response time degradations, network connectivity issues, and application unresponsiveness may not stump you.
Lots of bloggers are using Google AdSense now. It’s getting really popular. With AdSense, bloggers can make money by showing ads on their websites. Read this important article written by the experienced designers of the best website designing company in Delhi –
Break data silos with real-time connectivity using Confluent Cloud Connectorsconfluent
Connectors integrate Apache Kafka® with external data systems, enabling you to move away from a brittle spaghetti architecture to one that is more streamlined, secure, and future-proof. However, if your team still spends multiple dev cycles building and managing connectors using just open source Kafka Connect, it’s time to consider a faster and cost-effective alternative.
AI Chatbot Development – A Comprehensive Guide .pdfayushiqss
Discover how generative AI is transforming IT development in this blog. Learn how using AI software development, artificial intelligence tools, and generative AI tools can lead to smarter, faster, and more efficient software creation. Explore real-world applications and see how these technologies are driving innovation and cutting costs in IT development.
@Call @Girls in Surat 🐱🐉 XXXXXXXXXX 🐱🐉 Best High Class Surat Avaulable
Functional programming in C++
1. Functional programming in C++
Alex Bolboacă, @alexboly, alex.bolboaca@mozaicworks.com
February 2018
2. Intro
A practical view on functional programming
Mindset
Core Building Blocks
Improve design with functional programming
Bad design with functional programming
OOP and functional programming
Conclusions
4. Why I care about functional programming
I identify with the software craft movement
5. Learning & Improving
I want to learn as much as possible about my craft.
The evolution of the software industry is just recycling old ideas, and
functional programming is old.
All programming languages support functional constructs today.
More restrictions on code (eg. immutability) lead to better code and better
designs.
7. Disclaimer
The code on the slides may be simplified for presentation purpose.
Find the valid examples on github: https://github.com/alexboly and
https://github.com/MozaicWorks
8. My First Touch of Functional Programming
(defun sqrt-iter (guess x)
(if (good-enough-p guess x)
guess
(sqrt-iter (improve guess x) x)))
Source: Professor Forrest Young, Psych 285
9. What is a monad?
The essence of monad is thus separation of
composition timeline from the composed
computation’s execution timeline, as well as the ability
of computation to implicitly carry extra data, as
pertaining to the computation itself, in addition to its
one (hence the name) output, that it will produce when
run (or queried, or called upon).
Source: https://wiki.haskell.org/Monad
10. A shorter explanation
All told, a monad in X is just a monoid in the category
of endofunctors of X, with product × replaced by
composition of endofunctors and unit set by the
identity endofunctor.
Saunders Mac Lane, “Categories for the Working Mathematician”
11. But don’t worry, just learn Category Theory
Category theory formalizes mathematical structure
and its concepts in terms of a labeled directed graph
called a category, whose nodes are called objects, and
whose labelled directed edges are called arrows (or
morphisms). A category has two basic properties: the
ability to compose the arrows associatively and the
existence of an identity arrow for each object.
…
Category theory has practical applications in
programming language theory, for example the usage
of monads in functional programming.
Wikipedia
14. What I thought it was:
A way of writing unreadable code with many parantheses, with a strange
order of operations, in a community that likes complicated explanations
15. How I understand it now:
A style of software design that focuses on functions and immutability to
simplify code, to allow removal of certain types of duplication, and to show
intent better
18. Functional programming
Start from input data and apply a set of transformations to get it to the
desired output.
Key ideas: pure data structures and pure functions
19. Example 1: increment all elements of a list
Structured programming:
incrementAllElements(list& aList){
for(int i = 0; i < aList.size(); ++i){
aList[i] ++;
}
}
Functional programming:
//Simplified C++ code
transform(aList, [](const int item){ return item + 1 });
20. Example 2: Get a string with 5 ‘t’ characters
Structured programming:
string result;
for(int i = 0; i < 5; ++i){
result += ’t’;
}
21. Example 2 (cont’d)
Functional programming:
// Data in: a range from 1 to 5
// Data out: a string with 5 ’t’
// Transformations: transform each element from range
// to ’t’(map), then join them (reduce)
// Groovy code
[1..5].collect{’t’}.join()
// C++ doesn’t support it yet, except for boost
// Simplified C++ code using boost’s irange
transform(irange(1, 5), [](){return ’t’;});
22. Example 3: Pacman moves on a line to the right
OOP
Let’s create classes for: Pacman, Board, Wall, Dot, Movement etc.
23. Example 3 (cont’d)
Functional programming
Data in: a line with pacman on it
……>……
Data out: a line with pacman moving one square to the right, and a missing
dot
…… >…..
Transformations:
• Get everything before pacman
• Get everything after pacman
• Create a new line formed from: everything before pacman, an empty
space, pacman, everything after pacman except first element
24. Example 3 (cont’d)
const Line tick(const Line& initialLine){
return (
beforePacman(initialLine) +
KindOfToken::Empty +
KindOfToken::Pacman +
removeFirst(afterPacman(initialLine))
);
}
Full example at: https://github.com/alexboly/pacmanCpp/
25. Conclusion
FP mindset: Data in -> Transformations -> Data out
Each transformation is a pure function, except at the edge of the system
(I/O).
27. Pure functions
A function that returns the same output whenever receiving the same input
In C++ const is your friend
28. Example: Not pure function
list.insert(5); // throws exception if too many elements
// otherwise, adds 5 to the list
29. Example: Pure function
const list insert(const list& aList, const int value) { ... };
newList = insert(aList, 5);
// always has the same behavior
// when passing in the same arguments
// unless externalities (eg. memory is full)
// Immutability!
30. Example: Immutable data structures
Immutable C++ example: https://github.com/rsms/immutable-cpp
auto a = Array<int>::empty();
a = a->push(1);
a = a->push(2);
a = a->push(3);
31. Lambdas / Anonymous functions
// Lambda variable
auto increment = [](auto value){return value + 1;};
assert(increment(2) == 3);
32. Lambda variable with specific captured context
int valueFromContext = 10;
auto appendValueFromContext =
[const auto valueFromContext](auto value){
return value + valueFromContext;
};
assert(appendValueFromContext(10) == 20);
33. Lambda variable capturing all used variables by copy
int valueFromContext = 10;
auto appendValueFromContext =
[=](auto value){
return value + valueFromContext;
};
assert(appendValueFromContext(10) == 20);
More details:
http://en.cppreference.com/w/cpp/language/lambda
37. Currying
// Without curry
list = add(list, 5);
list = add(list, 1000);
// With curry (bind in C++ 11)
auto addToEmptyList = bind(add, list<int>(), _1);
assert addToEmptyList(5) == list<int>({5});
assert addToEmptyList(1000) == list<int>({1000});
38. Functional composability
auto threeElementsList = [](int first, int second, int third){
return add(add(addToEmptyList(first), second), third);
};
// In some programming languages,
// composing functions has its own syntax
// Eg. Groovy
def oneElementList = add << addToEmptyList
// same as add(addToEmptyList(), _)
assert(threeElementsList(0, 1, 2) == list<int>({0, 1, 2}));
39. Currying and composability
auto addTwoElementsToEmptyList = [](const int first, const int
return add(addToEmptyList(first), second);
};
auto listWith0And1 = bind(addTwoElementsToEmptyList, 0, 1);
assert(listWith0And1() == list<int>({0, 1});
40. Higher level functionvalues
We can pass functions as parameters
auto incrementFunctionResult = [](const auto aFunction){
return aFunction() + 1;
};
auto function1 = [](){
return 1;
};
assert(incrementFunctionResult(function1) == 2);
41. Short list of higher level functions
Find them in or
• find_if
• transform
• reduce / accumulate
• count_if
• all_of / any_of / none_of
• …
See examples on https://github.com/MozaicWorks/functionalCpp
42. Almost anything can be a function
//TRUE = {x -> { y -> x}}
auto TRUE = [](auto x){
return [x](auto y){
return x;
};
};
//FALSE = {x -> { y -> y}}
auto FALSE = [](auto x){
return [](auto y){
return y;
};
};
43. Church encoding for booleans (cont’d)
//IF = {proc -> { x -> { y -> proc(x)(y) }}}
auto IF = [](auto proc){
return [proc](auto x){
return [x, proc](auto y){
return proc(x)(y);
};
};
};
CHECK(IF(TRUE)(”foo”)(”bar”) == ”foo”);
Source: https://github.com/alexboly/ChurchEncodingCpp
44. Conclusions
• Pure functions are the basic building blocks of functional programming
• The best functions are small and polymorphic
• When the same parameter is passed to multiple function calls,
consider using curry (bind in C++)
• When the return of a function is passed to another function multiple
times, consider using functional composition
• Reuse existing functions as much as possible: map (transform in C++),
reduce, find etc.
• Experiment with functional programming: TicTacToe score, pacman,
tetris
• Replace traditional loops with functional loops as much as possible
46. Clarify loops intent
for(auto element=list.begin(); element != list.end(); element++
// I have to read all of this to understand what the loop does
}
47. Functional loops
transform(....); // transform a collection into another!
auto increment = [](auto value){return value + 1;};
transform(list, increment); // transform a list into another
// with incremented elements
transform(list, increment); // compute the sum
// of all incremented elements
// compute the sum of all incremented even numbers
reduce(find(transform(list, increment), evenNumber), plus)
48. What about web apps?
Data in: an HTTP request
Data out: HTML + a response code + something saved in a store
Transformations:
• validation
• sanitization
• canonicalization
• business rules
• save to database (mutable!)
• or read from database (mutable!)
• convert to view
• pass on to html rendering
Everything in between request and database, and database and response,
is immutable!
54. Relationship between OOP and functional programming
A class is nothing more than a set of cohesive, partially applied pure
functions
– via JB Rainsberger
55. Remember first example?
// OOP version: Cohesion
class List{
private listStorage
add(element){....}
removeLast(){....}
}
// Functional version
add(list, element)
removeLast(list)
56. // Equivalence
def add = [](auto listStorage, auto element){return ....};
// For oop bind function parameters
// to the data members of the class
auto oopAdd = [](element){ return add(initialListStorage, eleme
// Or curry (bind)
def oopAdd = bind(add, initialListStorage)
oopAdd(5)
58. My thoughts
Good:
• Functional programming mindset is very useful for data-centric
applications
• Higher level functions simplify and clarify intent for data
transformations
• Pure functions are very easy to test
• Clear separation between mutable and immutable state simplifies
everything
59. Careful:
• Beware of too high abstraction & ensure your colleagues understand
the code
• Carefully mix OOP with functional constructs
60. Can’t ignore:
• Functional programming is here to stay due to CPUs going multicore
• New applications: big data, reactive programming etc.
• All modern languages have FP constructs built in
• Clojure, Scala, Haskell, F# are used and will be used
• AI is built using FP (composability)
62. Learn more at Mozaic Works workshops
https://mozaicworks.com/training/c-plus-plus/
63. Thank you!
I’ve been Alex Bolboacă, @alexboly, alex.bolboaca@mozaicworks.com
programmer, trainer, mentor, writer
at Mozaic Works
Think. Design. Work Smart.
https://mozaicworks.com