First in the series of slides for python programming, covering topics like programming language, python programming constructs, loops and control statements.
Workshop slides from the Alt.Net Seattle 2011 workshop. Presented by Wes Dyer and Ryan Riley. Get the slides and the workshop code at http://rxworkshop.codeplex.com/
First in the series of slides for python programming, covering topics like programming language, python programming constructs, loops and control statements.
Workshop slides from the Alt.Net Seattle 2011 workshop. Presented by Wes Dyer and Ryan Riley. Get the slides and the workshop code at http://rxworkshop.codeplex.com/
An overview of the programming techniques available and some of the ongoing research in the Haskell community around concurrent and parallel programming.
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/
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.
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.
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.
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.
An overview of the programming techniques available and some of the ongoing research in the Haskell community around concurrent and parallel programming.
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/
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.
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.
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.
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.
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 article may be interesting for developers who use or plan to use OpenC++ library (OpenCxx). The author tells about his experience of improving OpenC++ library and modifying the library for solving special tasks.
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.
Download this Presentation for free from www.ecti.co.in/downloads.html
No SIGN UP REQUIRED.
C++ Programming Training PPTs / PDFs for free.
Download free C++ Programming study material. Learn C++ Programming for free in 2 hours.
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.
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.
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.
Docker is a tool that didn't exist 2 years ago. Yet I am convinced that we will hear about it for a long time. We will almost certainly use containers to test and deploy our applications.
This talk is about the reasons to start using docker in your daily work as a programmer, tester, sysadmin or IT professional.
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.
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.
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.
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Mind IT Systems
Healthcare providers often struggle with the complexities of chronic conditions and remote patient monitoring, as each patient requires personalized care and ongoing monitoring. Off-the-shelf solutions may not meet these diverse needs, leading to inefficiencies and gaps in care. It’s here, custom healthcare software offers a tailored solution, ensuring improved care and effectiveness.
Check out the webinar slides to learn more about how XfilesPro transforms Salesforce document management by leveraging its world-class applications. For more details, please connect with sales@xfilespro.com
If you want to watch the on-demand webinar, please click here: https://www.xfilespro.com/webinars/salesforce-document-management-2-0-smarter-faster-better/
Developing Distributed High-performance Computing Capabilities of an Open Sci...Globus
COVID-19 had an unprecedented impact on scientific collaboration. The pandemic and its broad response from the scientific community has forged new relationships among public health practitioners, mathematical modelers, and scientific computing specialists, while revealing critical gaps in exploiting advanced computing systems to support urgent decision making. Informed by our team’s work in applying high-performance computing in support of public health decision makers during the COVID-19 pandemic, we present how Globus technologies are enabling the development of an open science platform for robust epidemic analysis, with the goal of collaborative, secure, distributed, on-demand, and fast time-to-solution analyses to support public health.
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Shahin Sheidaei
Games are powerful teaching tools, fostering hands-on engagement and fun. But they require careful consideration to succeed. Join me to explore factors in running and selecting games, ensuring they serve as effective teaching tools. Learn to maintain focus on learning objectives while playing, and how to measure the ROI of gaming in education. Discover strategies for pitching gaming to leadership. This session offers insights, tips, and examples for coaches, team leads, and enterprise leaders seeking to teach from simple to complex concepts.
Into the Box Keynote Day 2: Unveiling amazing updates and announcements for modern CFML developers! Get ready for exciting releases and updates on Ortus tools and products. Stay tuned for cutting-edge innovations designed to boost your productivity.
Quarkus Hidden and Forbidden ExtensionsMax Andersen
Quarkus has a vast extension ecosystem and is known for its subsonic and subatomic feature set. Some of these features are not as well known, and some extensions are less talked about, but that does not make them less interesting - quite the opposite.
Come join this talk to see some tips and tricks for using Quarkus and some of the lesser known features, extensions and development techniques.
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus
As part of the DOE Integrated Research Infrastructure (IRI) program, NERSC at Lawrence Berkeley National Lab and ALCF at Argonne National Lab are working closely with General Atomics on accelerating the computing requirements of the DIII-D experiment. As part of the work the team is investigating ways to speedup the time to solution for many different parts of the DIII-D workflow including how they run jobs on HPC systems. One of these routes is looking at Globus Compute as a way to replace the current method for managing tasks and we describe a brief proof of concept showing how Globus Compute could help to schedule jobs and be a tool to connect compute at different facilities.
First Steps with Globus Compute Multi-User EndpointsGlobus
In this presentation we will share our experiences around getting started with the Globus Compute multi-user endpoint. Working with the Pharmacology group at the University of Auckland, we have previously written an application using Globus Compute that can offload computationally expensive steps in the researcher's workflows, which they wish to manage from their familiar Windows environments, onto the NeSI (New Zealand eScience Infrastructure) cluster. Some of the challenges we have encountered were that each researcher had to set up and manage their own single-user globus compute endpoint and that the workloads had varying resource requirements (CPUs, memory and wall time) between different runs. We hope that the multi-user endpoint will help to address these challenges and share an update on our progress here.
A Comprehensive Look at Generative AI in Retail App Testing.pdfkalichargn70th171
Traditional software testing methods are being challenged in retail, where customer expectations and technological advancements continually shape the landscape. Enter generative AI—a transformative subset of artificial intelligence technologies poised to revolutionize software testing.
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar
The European Union Agency for Law Enforcement Cooperation (Europol) has suffered an alleged data breach after a notorious threat actor claimed to have exfiltrated data from its systems. Infamous data leaker IntelBroker posted on the even more infamous BreachForums hacking forum, saying that Europol suffered a data breach this month.
The alleged breach affected Europol agencies CCSE, EC3, Europol Platform for Experts, Law Enforcement Forum, and SIRIUS. Infiltration of these entities can disrupt ongoing investigations and compromise sensitive intelligence shared among international law enforcement agencies.
However, this is neither the first nor the last activity of IntekBroker. We have compiled for you what happened in the last few days. To track such hacker activities on dark web sources like hacker forums, private Telegram channels, and other hidden platforms where cyber threats often originate, you can check SOCRadar’s Dark Web News.
Stay Informed on Threat Actors’ Activity on the Dark Web with SOCRadar!
Navigating the Metaverse: A Journey into Virtual Evolution"Donna Lenk
Join us for an exploration of the Metaverse's evolution, where innovation meets imagination. Discover new dimensions of virtual events, engage with thought-provoking discussions, and witness the transformative power of digital realms."
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamtakuyayamamoto1800
In this slide, we show the simulation example and the way to compile this solver.
In this solver, the Helmholtz equation can be solved by helmholtzFoam. Also, the Helmholtz equation with uniformly dispersed bubbles can be simulated by helmholtzBubbleFoam.
Unleash Unlimited Potential with One-Time Purchase
BoxLang is more than just a language; it's a community. By choosing a Visionary License, you're not just investing in your success, you're actively contributing to the ongoing development and support of BoxLang.
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisGlobus
JASMIN is the UK’s high-performance data analysis platform for environmental science, operated by STFC on behalf of the UK Natural Environment Research Council (NERC). In addition to its role in hosting the CEDA Archive (NERC’s long-term repository for climate, atmospheric science & Earth observation data in the UK), JASMIN provides a collaborative platform to a community of around 2,000 scientists in the UK and beyond, providing nearly 400 environmental science projects with working space, compute resources and tools to facilitate their work. High-performance data transfer into and out of JASMIN has always been a key feature, with many scientists bringing model outputs from supercomputers elsewhere in the UK, to analyse against observational or other model data in the CEDA Archive. A growing number of JASMIN users are now realising the benefits of using the Globus service to provide reliable and efficient data movement and other tasks in this and other contexts. Further use cases involve long-distance (intercontinental) transfers to and from JASMIN, and collecting results from a mobile atmospheric radar system, pushing data to JASMIN via a lightweight Globus deployment. We provide details of how Globus fits into our current infrastructure, our experience of the recent migration to GCSv5.4, and of our interest in developing use of the wider ecosystem of Globus services for the benefit of our user community.
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Globus
The Earth System Grid Federation (ESGF) is a global network of data servers that archives and distributes the planet’s largest collection of Earth system model output for thousands of climate and environmental scientists worldwide. Many of these petabyte-scale data archives are located in proximity to large high-performance computing (HPC) or cloud computing resources, but the primary workflow for data users consists of transferring data, and applying computations on a different system. As a part of the ESGF 2.0 US project (funded by the United States Department of Energy Office of Science), we developed pre-defined data workflows, which can be run on-demand, capable of applying many data reduction and data analysis to the large ESGF data archives, transferring only the resultant analysis (ex. visualizations, smaller data files). In this talk, we will showcase a few of these workflows, highlighting how Globus Flows can be used for petabyte-scale climate analysis.
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteGoogle
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
👉👉 Click Here To Get More Info 👇👇
https://sumonreview.com/ai-pilot-review/
AI Pilot Review: Key Features
✅Deploy AI expert bots in Any Niche With Just A Click
✅With one keyword, generate complete funnels, websites, landing pages, and more.
✅More than 85 AI features are included in the AI pilot.
✅No setup or configuration; use your voice (like Siri) to do whatever you want.
✅You Can Use AI Pilot To Create your version of AI Pilot And Charge People For It…
✅ZERO Manual Work With AI Pilot. Never write, Design, Or Code Again.
✅ZERO Limits On Features Or Usages
✅Use Our AI-powered Traffic To Get Hundreds Of Customers
✅No Complicated Setup: Get Up And Running In 2 Minutes
✅99.99% Up-Time Guaranteed
✅30 Days Money-Back Guarantee
✅ZERO Upfront Cost
See My Other Reviews Article:
(1) TubeTrivia AI Review: https://sumonreview.com/tubetrivia-ai-review
(2) SocioWave Review: https://sumonreview.com/sociowave-review
(3) AI Partner & Profit Review: https://sumonreview.com/ai-partner-profit-review
(4) AI Ebook Suite Review: https://sumonreview.com/ai-ebook-suite-review
In software engineering, the right architecture is essential for robust, scalable platforms. Wix has undergone a pivotal shift from event sourcing to a CRUD-based model for its microservices. This talk will chart the course of this pivotal journey.
Event sourcing, which records state changes as immutable events, provided robust auditing and "time travel" debugging for Wix Stores' microservices. Despite its benefits, the complexity it introduced in state management slowed development. Wix responded by adopting a simpler, unified CRUD model. This talk will explore the challenges of event sourcing and the advantages of Wix's new "CRUD on steroids" approach, which streamlines API integration and domain event management while preserving data integrity and system resilience.
Participants will gain valuable insights into Wix's strategies for ensuring atomicity in database updates and event production, as well as caching, materialization, and performance optimization techniques within a distributed system.
Join us to discover how Wix has mastered the art of balancing simplicity and extensibility, and learn how the re-adoption of the modest CRUD has turbocharged their development velocity, resilience, and scalability in a high-growth environment.
We describe the deployment and use of Globus Compute for remote computation. This content is aimed at researchers who wish to compute on remote resources using a unified programming interface, as well as system administrators who will deploy and operate Globus Compute services on their research computing infrastructure.
Cyaniclab : Software Development Agency Portfolio.pdfCyanic lab
CyanicLab, an offshore custom software development company based in Sweden,India, Finland, is your go-to partner for startup development and innovative web design solutions. Our expert team specializes in crafting cutting-edge software tailored to meet the unique needs of startups and established enterprises alike. From conceptualization to execution, we offer comprehensive services including web and mobile app development, UI/UX design, and ongoing software maintenance. Ready to elevate your business? Contact CyanicLab today and let us propel your vision to success with our top-notch IT solutions.
Cyaniclab : Software Development Agency Portfolio.pdf
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