(video of these slides available here http://fsharpforfunandprofit.com/fppatterns/)
In object-oriented development, we are all familiar with design patterns such as the Strategy pattern and Decorator pattern, and design principles such as SOLID.
The functional programming community has design patterns and principles as well.
This talk will provide an overview of some of these, and present some demonstrations of FP design in practice.
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
An Introduction to Functional Programming - DeveloperUG - 20140311Andreas Pauley
Functional Programming has received increased attention in recent years.
Some people claim that it provides important benefits to programming, but it seems somewhat inaccessible. You have to navigate through lots of academic-speak and look at examples that might only make sense to a professor in mathematics.
In this presentation I try to present some of the essential ideas behind functional programming, with simple examples first in Python and then in Haskell.
What do you need to know in order to enjoy this talk?
I have made some of the following assumptions about the kind of developer who will benefit from this talk:
1. You are a programmer using any programming language
2. You can read Python examples (it's WAY shorter on slides than C# or Java)
3. You are interested enough in improving your code that you are willing to challenge some common assumptions.
Introduction to Functional Programming in JavaScripttmont
A presentation I did for work on functional programming. It's meant as an introduction to functional programming, and I implemented the fundamentals of functional programming (Church Numerals, Y-Combinator, etc.) in JavaScript.
The emergence of support of functions and lambda expressions as first-class citizens in Java 8 gives us a tremendous opportunity to adapt the concepts of functional programming to the Java language.
(video of these slides available here http://fsharpforfunandprofit.com/fppatterns/)
In object-oriented development, we are all familiar with design patterns such as the Strategy pattern and Decorator pattern, and design principles such as SOLID.
The functional programming community has design patterns and principles as well.
This talk will provide an overview of some of these, and present some demonstrations of FP design in practice.
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
An Introduction to Functional Programming - DeveloperUG - 20140311Andreas Pauley
Functional Programming has received increased attention in recent years.
Some people claim that it provides important benefits to programming, but it seems somewhat inaccessible. You have to navigate through lots of academic-speak and look at examples that might only make sense to a professor in mathematics.
In this presentation I try to present some of the essential ideas behind functional programming, with simple examples first in Python and then in Haskell.
What do you need to know in order to enjoy this talk?
I have made some of the following assumptions about the kind of developer who will benefit from this talk:
1. You are a programmer using any programming language
2. You can read Python examples (it's WAY shorter on slides than C# or Java)
3. You are interested enough in improving your code that you are willing to challenge some common assumptions.
Introduction to Functional Programming in JavaScripttmont
A presentation I did for work on functional programming. It's meant as an introduction to functional programming, and I implemented the fundamentals of functional programming (Church Numerals, Y-Combinator, etc.) in JavaScript.
The emergence of support of functions and lambda expressions as first-class citizens in Java 8 gives us a tremendous opportunity to adapt the concepts of functional programming to the Java language.
This is continuation of the slide Advanced C part 1. In part 1 you learnt about fundamentals of C - How to build an algorithm, operators. In this module - Advanced C part 2 you will be learning about functions, pointers and standard Input Output functions. This slide will help you to move a further ahead in Advanced C and gain deeper knowledge on it.
First part of this presentation explains basics and advantages of using functional programming approaches with lambda calculus.
Second part of this presentation explains how can we use lambda calculus in C# 3.0
Video and more content at fsharpforfunandprofit.com/pbt
"The lazy programmer's guide to writing 1000's of tests: An introduction to property based testing"
We are all familiar with example-based testing, as typified by TDD and BDD. Property-based testing takes a very different approach, where a single test is run hundreds of times with randomly generated inputs.
Property-based testing is a great way to find edge cases, and also helps you to understand and document the behaviour of your code under all conditions.
This talk will introduce property-based testing and show how it works, and why you should consider adding it to your arsenal of testing tools.
Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...Philip Schwarz
(download for picture-perfect quality) Follow along as the impure functions in the Game of Life are translated from Haskell into Scala, deepening you understanding of the IO monad in the process.
This is simply a copy of the original with an error corrected on slides 3 and 52, which were supposed to show Scala code and instead showed the Haskell equivalent! Plus removal of a few minor aesthetic imperfections.
Original: https://www.slideshare.net/pjschwarz/game-of-life-polyglot-fp-haskell-scala-unison-part-2
After a recap of implicits I introduce the type class mechanics in Scala. Then I have a look at ways for good non-intrusive type class design. The main focus of this presentation are type classes in Scala. In the last chapter I show the Haskell implementation of my example.
https://www.dmdiploma.com/studymaterial?id=5/python-for-data-science
This Python course provides a beginner-friendly introduction to Python for Data Science.
This is continuation of the slide Advanced C part 1. In part 1 you learnt about fundamentals of C - How to build an algorithm, operators. In this module - Advanced C part 2 you will be learning about functions, pointers and standard Input Output functions. This slide will help you to move a further ahead in Advanced C and gain deeper knowledge on it.
First part of this presentation explains basics and advantages of using functional programming approaches with lambda calculus.
Second part of this presentation explains how can we use lambda calculus in C# 3.0
Video and more content at fsharpforfunandprofit.com/pbt
"The lazy programmer's guide to writing 1000's of tests: An introduction to property based testing"
We are all familiar with example-based testing, as typified by TDD and BDD. Property-based testing takes a very different approach, where a single test is run hundreds of times with randomly generated inputs.
Property-based testing is a great way to find edge cases, and also helps you to understand and document the behaviour of your code under all conditions.
This talk will introduce property-based testing and show how it works, and why you should consider adding it to your arsenal of testing tools.
Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...Philip Schwarz
(download for picture-perfect quality) Follow along as the impure functions in the Game of Life are translated from Haskell into Scala, deepening you understanding of the IO monad in the process.
This is simply a copy of the original with an error corrected on slides 3 and 52, which were supposed to show Scala code and instead showed the Haskell equivalent! Plus removal of a few minor aesthetic imperfections.
Original: https://www.slideshare.net/pjschwarz/game-of-life-polyglot-fp-haskell-scala-unison-part-2
After a recap of implicits I introduce the type class mechanics in Scala. Then I have a look at ways for good non-intrusive type class design. The main focus of this presentation are type classes in Scala. In the last chapter I show the Haskell implementation of my example.
https://www.dmdiploma.com/studymaterial?id=5/python-for-data-science
This Python course provides a beginner-friendly introduction to Python for Data Science.
Work common problems out via a functional approach. Think in terms of functions, be lazy, use pipelines and handle concurrency with immutable data borrowing concepts from Haskell/Scala/Erlang. All of this in Python.
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docxvrickens
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition pg. 25
An Introduction to
Computer Science with Java, Python and C++
Community College of Philadelphia edition
Copyright 2017 by C.W. Herbert, all rights reserved.
Last edited October 8, 28, 2019 by C. W. Herbert
This document is a draft of a chapter from An Introduction to Computer Science with Java, Python and C++, written by Charles Herbert. It is available free of charge for students in Computer Science courses at Community College of Philadelphia during the Fall 2019 semester. It may not be reproduced or distributed for any other purposes without proper prior permission.
Please report any typos, other errors, or suggestions for improving the text to [email protected]
Chapter 5 – Python Functions and Modular Programming
Contents
Lesson 5.1User Created Functions in Python2
Python Function Parameters2
Value returning functions3
Example – Methods and Parameter Passing5
9
Lesson 5.2Top-Down Design and Modular Development10
Chapter Exercises13
User Created Functions in Python
So far we have only created software with one continuous Python script. We have used functions from other python modules, such as the square root method from the math class math.sqrt(n). Now we will begin to create our own functions of our own.
A Python function is a block of code that can be used to perform a specific task within a larger computer program. It can be called as needed from other Python software. Most programming languages have similar features, such as methods in Java or subroutines in system software.
The code for user-defined functions in Python is contained in a function definition. A Python function definition is a software unit with a header and a block of Python statements. The header starts with the keyword def followed by the name of the function, then a set parenthesis with any parameters for the function. A colon is used after the parentheses to indicate a block of code follows, just as with the if and while statements. The block of code to be included within the function is indented.
Here is an example of a Python function:
# firstFunction.py
# first demonstration of the use of a function for CSCI 111
# last edited 10/08/2o19 by C. Herbert
function
definition
def myFunction():
print ( "This line being printed by the function MyFunction.\n")
# end myFunction()
### main program ###
function used by the main part of the script
print("Beginning\n")
myFunction()
print("End\n")
# end main program
Functions can used for code that will be repeated within a program, or for modular development, in which long programs are broken into parts and the parts are developed independently. The parts can be developed as Python functions, then integrated to work together by being called from other software.
Python Function Parameters
Data can be passed to a Python function as a parameter of the function. Function parameters are variables listed in parentheses foll ...
Design principles to modularise a monolith codebase.pptxPrashant Kalkar
In this talk, we will discuss
How a good module look like (Discussion on module boundaries - Reusable code).
Properties of good reusable code.
Principles that help get the module boundaries right (cohesion principles)
Principles to manage dependencies between the modules (coupling principles).
Tools that can be used to decouple the code base. (We will be using IntelliJ Idea DSM to visualise the code base dependencies and to break them).
Techniques that can help to prevent future issues.
We won't be covering all the principles or every aspect of the given principles due to time constrain. Main goal of the talk is to provide actionable points and to have a healthy discussion around the same.
Exploring the flow of network traffic through kubernetes cluster.pptxPrashant Kalkar
https://www.meetup.com/devday_pune/events/287898343/
The modern kubernetes cluster hosts a range of services ranging from 10 to 100. Every service with multiple pods might scale out or scale in. Further, a unified application url is exposed to outside world masking the complexity of micro-services. How does a request flow through the kubernetes and cloud infrastructure and reach a single pod? How does kubernetes networking make the request flow to the destination pod?
What role do concepts like Pod IPs, cluster IP services, node port services, ingress records etc play in exposing the kubernetes applications? In this talk, we will explore
Inter pod connectivity with Pod IPs.
The need for kubernetes services.
What is a clusterIP service?
What is a nodeIP service?
What is a load balancer service?
Why do we need ingress records and ingress controller?
How does ingress controller receive traffic?
How does AWS load balancer send traffic to kubernetes services from outside of cluster (without really knowing that traffic is going to kubernetes cluster)?
Uncover the mysteries of infrastructure as code (iac)!Prashant Kalkar
In the era of cloud and containerisation, infrastructure as code (IAC) is invaluable. In this talk, we will explore the evolution of Infrastructure practices and tools. We will further look at the practices and tools before the emergence of the clouds. Then we will explore how the rise of the cloud changed the infrastructure automation practices and made the IAC a mainstream practice.
We will also explore what it means to treat infrastructure as code. We will talk about Code vs Configuration, versioning, Configurability vs Standardisation, Modularity and code organisation for infrastructure code.
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."
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
Large Language Models and the End of ProgrammingMatt Welsh
Talk by Matt Welsh at Craft Conference 2024 on the impact that Large Language Models will have on the future of software development. In this talk, I discuss the ways in which LLMs will impact the software industry, from replacing human software developers with AI, to replacing conventional software with models that perform reasoning, computation, and problem-solving.
Enhancing Research Orchestration Capabilities at ORNL.pdfGlobus
Cross-facility research orchestration comes with ever-changing constraints regarding the availability and suitability of various compute and data resources. In short, a flexible data and processing fabric is needed to enable the dynamic redirection of data and compute tasks throughout the lifecycle of an experiment. In this talk, we illustrate how we easily leveraged Globus services to instrument the ACE research testbed at the Oak Ridge Leadership Computing Facility with flexible data and task orchestration capabilities.
Software Engineering, Software Consulting, Tech Lead.
Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Security,
Spring Transaction, Spring MVC,
Log4j, REST/SOAP WEB-SERVICES.
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.
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.
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Globus
Large Language Models (LLMs) are currently the center of attention in the tech world, particularly for their potential to advance research. In this presentation, we'll explore a straightforward and effective method for quickly initiating inference runs on supercomputers using the vLLM tool with Globus Compute, specifically on the Polaris system at ALCF. We'll begin by briefly discussing the popularity and applications of LLMs in various fields. Following this, we will introduce the vLLM tool, and explain how it integrates with Globus Compute to efficiently manage LLM operations on Polaris. Attendees will learn the practical aspects of setting up and remotely triggering LLMs from local machines, focusing on ease of use and efficiency. This talk is ideal for researchers and practitioners looking to leverage the power of LLMs in their work, offering a clear guide to harnessing supercomputing resources for quick and effective LLM inference.
Understanding Globus Data Transfers with NetSageGlobus
NetSage is an open privacy-aware network measurement, analysis, and visualization service designed to help end-users visualize and reason about large data transfers. NetSage traditionally has used a combination of passive measurements, including SNMP and flow data, as well as active measurements, mainly perfSONAR, to provide longitudinal network performance data visualization. It has been deployed by dozens of networks world wide, and is supported domestically by the Engagement and Performance Operations Center (EPOC), NSF #2328479. We have recently expanded the NetSage data sources to include logs for Globus data transfers, following the same privacy-preserving approach as for Flow data. Using the logs for the Texas Advanced Computing Center (TACC) as an example, this talk will walk through several different example use cases that NetSage can answer, including: Who is using Globus to share data with my institution, and what kind of performance are they able to achieve? How many transfers has Globus supported for us? Which sites are we sharing the most data with, and how is that changing over time? How is my site using Globus to move data internally, and what kind of performance do we see for those transfers? What percentage of data transfers at my institution used Globus, and how did the overall data transfer performance compare to the Globus users?
Utilocate offers a comprehensive solution for locate ticket management by automating and streamlining the entire process. By integrating with Geospatial Information Systems (GIS), it provides accurate mapping and visualization of utility locations, enhancing decision-making and reducing the risk of errors. The system's advanced data analytics tools help identify trends, predict potential issues, and optimize resource allocation, making the locate ticket management process smarter and more efficient. Additionally, automated ticket management ensures consistency and reduces human error, while real-time notifications keep all relevant personnel informed and ready to respond promptly.
The system's ability to streamline workflows and automate ticket routing significantly reduces the time taken to process each ticket, making the process faster and more efficient. Mobile access allows field technicians to update ticket information on the go, ensuring that the latest information is always available and accelerating the locate process. Overall, Utilocate not only enhances the efficiency and accuracy of locate ticket management but also improves safety by minimizing the risk of utility damage through precise and timely locates.
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.
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxrickgrimesss22
Discover the essential features to incorporate in your Winzo clone app to boost business growth, enhance user engagement, and drive revenue. Learn how to create a compelling gaming experience that stands out in the competitive market.
How to Position Your Globus Data Portal for Success Ten Good PracticesGlobus
Science gateways allow science and engineering communities to access shared data, software, computing services, and instruments. Science gateways have gained a lot of traction in the last twenty years, as evidenced by projects such as the Science Gateways Community Institute (SGCI) and the Center of Excellence on Science Gateways (SGX3) in the US, The Australian Research Data Commons (ARDC) and its platforms in Australia, and the projects around Virtual Research Environments in Europe. A few mature frameworks have evolved with their different strengths and foci and have been taken up by a larger community such as the Globus Data Portal, Hubzero, Tapis, and Galaxy. However, even when gateways are built on successful frameworks, they continue to face the challenges of ongoing maintenance costs and how to meet the ever-expanding needs of the community they serve with enhanced features. It is not uncommon that gateways with compelling use cases are nonetheless unable to get past the prototype phase and become a full production service, or if they do, they don't survive more than a couple of years. While there is no guaranteed pathway to success, it seems likely that for any gateway there is a need for a strong community and/or solid funding streams to create and sustain its success. With over twenty years of examples to draw from, this presentation goes into detail for ten factors common to successful and enduring gateways that effectively serve as best practices for any new or developing gateway.
Top 7 Unique WhatsApp API Benefits | Saudi ArabiaYara Milbes
Discover the transformative power of the WhatsApp API in our latest SlideShare presentation, "Top 7 Unique WhatsApp API Benefits." In today's fast-paced digital era, effective communication is crucial for both personal and professional success. Whether you're a small business looking to enhance customer interactions or an individual seeking seamless communication with loved ones, the WhatsApp API offers robust capabilities that can significantly elevate your experience.
In this presentation, we delve into the top 7 distinctive benefits of the WhatsApp API, provided by the leading WhatsApp API service provider in Saudi Arabia. Learn how to streamline customer support, automate notifications, leverage rich media messaging, run scalable marketing campaigns, integrate secure payments, synchronize with CRM systems, and ensure enhanced security and privacy.
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/
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.
2. Shortcoming of current model.
What is Functional Programming (FP).
Benefits of Functional Programming.
Explore side effects and eliminate them.
Higher order functions and lambda expressions.
Collection processing in FP.
Declarative Programming.
Some more benefits in FP.
FP vs OO and when to use them.
Agenda
3. Takeaways
What is FP.
Why to use FP.
Initiate the thinking in FP.
Techniques to eliminate side effects.
Structure of functional code base.
Structural difference between FP and OO
When to use FP solution.
When to use OO solution.
5. Consider Example
int f() {
y = y + 1; return y;
}
What is the output of function call
f()?
Requires or depends on
external state.
Need to know the history of
interactions with the
system.
Multiple calls will cause side
effects.
y = 1 // initial value
Now what will be the output?
6. State of Ellipse
Ellipse ellipse = new Ellipse(new Rectangle(0, 0, 100, 100));
BoundingBox boundingBox = ellipse.boundingBox;
boundingBox.inflate(10, 10);
Mutation in object graph affect many graph objects
Tracking change is difficult.
7. boolean hitMonster = monster.hitByShooting(gunShot);
boolean hitPlayer = player.hitByShooting(gunShot);
Are these statements independent of each other?
Mutation impose order.
8. Solutions?
Clause of issue was mutation in the programs. More
precisely global mutation.
Let put in some constrains on functions
Only depend on the input parameters.
For same input, same output.
No mutation of state.
9. int f(int y) { return y + 1; }
Now what will be the output of functional call f(5)?
Ellipse ellipse = new Ellipse(new Rectangle(0, 0, 100, 100));
BoundingBox boundingBox = ellipse.boundingBox;
boundingBox.inflate(10, 10);
If everything is immutable, what will be state of Ellipse after
these operations?
10. We defined a true Mathematical expression
Only depend on the input parameters.
For same input, same output.
No mutation of state or Side effects
Also called as Pure functions.
Functional programming is programming with Pure functions.
11. Functional Programming
In computer science, functional programming is a
programming paradigm—a style of building the structure
and elements of computer programs—that treats
computation as the evaluation of mathematical
functions and avoids changing-state and mutable data.
- Wikipedia
13. int x = 2 * 3 + 5;
Is it an expression?
= Expression
= Expression
= Statement (requires mutation)
= Statement (requires mutation)
= Expression
= Expression (mutation is avoided)
int x = a < 5 ? 5 : a;
if(a < 5) { x = 5; } else { x = a; }
val x = if(a < 5) 5 else a (scala)
for(int i=0; i<a.length;i++) b[i]= a[i] * 2;
val b = for(i <- a) yield i * 2 (scala)
14. Benefits of Pure functions
Context Independent
Depends only on parameters.
Highly reusable
Because they are context independent.
Can be reasoned Locally
Everything is in the function body.
Highly testable.
15. Can be reasoned Locally?
It's ok, for small functions
What about functions that are calling other
complex functions.
Referential Transparency & Substitution Model
16. Referential Transparency
If a program can be updated by replacing the function call
with result of the function call without changing its
behaviour then that function is Referentially Transparent
Function.
17. Example
int square(int a) { return a * a; }
int x = square(4); => x = 16;
Replacing square(4) with 16 will not change the behaviour
of the program.
So function square is Referentially transparent
18. Substitution Model
Substitution model is a model of reasoning a program by
substituting the referentially transparent functions with their
values.
This makes the understanding of complex program easy.
This enables the local reasoning of the functions.
And a good name for a function helps.
19. View of Function in FP world
What do you think when you think of a Function in
conventional languages?
We think in terms of what that function does.
In FP you think only about input and output types.
def f1: String => Int = ???
def f2: Int => Boolean = ???
def f3[A, B]: A => B = ???
20. Benefits of FP View
Functions become more composable.
System become more modular.
Higher order functions are possible.
They just care whether function arguments follow a
type signature.
23. boolean hitMonster = monster.hitByShooting(gunShot);
// reduce the power of the
gunshot
boolean hitPlayer = player.hitByShooting(gunShot);
What is a side effect?
24. Code inside monster class
boolean hitByShooting(Gunshot gunShot) {
if(isInRange()) {
gunShot.reducePower();
return true;
}
return false;
}
<= Happening on the side
Not visible through return type.
Not Referentially Transparent function (can not be substituted)
25. Types of Side effects
Mutation of value.
Throwing an Exception.
I/O operations like printing or File operations.
Communicating with DB.
Remote communication.
27. def hitByShooting(gunShot : Gunshot): (Boolean, Gunshot) = {
if(isInRange()) {
val usedGunshot = gunShot.reducePower()
(true, usedGunshot)
} else
(false, gunShot)
}
Referentially Transparent Function (can be substituted).
Visible in returned value
No more a side
effect
28. val (hitMonster, usedGunshot) = monster.hitByShooting(gunShot)
// reduce the power of the gunshot
val hitPlayer = player.hitByShooting(usedGunshot)
Inter-dependency is now visible in the code.
Types of pure functions make the dependency visible.
30. Traditional Testing with DI
def draw(ds: DisplayService) = {
ds.println("-" * (width + 2))
rows.foreach { row =>
ds.println("|" + row.map(p => p.toString).mkString + "|")
}
ds.println("-" * (width + 2))
}
Injected & mocked during tests.
31. Functional Implementation
def canvasAsString(): String = {
val topBorder = "-" * (width + 2) + "n"
val canvasRows = rowAsString()
val bottomBorder = "-" * (width + 2)
topBorder + canvasRows + bottomBorder
}
println(canvasAsString()) // only line in program with side effect.
32. Another example
Buying coffee
class Cafe {
def buyCoffee(cc: CreditCard): Coffee = {
val cup = new Coffee()
cc.charge(cup.price)
cup
}
}
Clearly a side effect.
33. Delaying the side effect
class Cafe {
def buyCoffe(cc: CreditCard): (Coffe, Charge) = {
val cup = new Coffee()
(cup, Charge(cc, cup.price))
// charge details are returned instead of processed
}
}
Here we’ve separated the concern of creating a charge from the
processing or interpretation of that charge.
34. Buying multiple coffees
Buy multiple cups of coffee with a single charge on credit
card.
def buyCoffees(cc: CreditCard, n: Int) : (List[Coffee], Charge)
// call buyCoffee n times
// combine n changes into a single charge on credit card.
This was possible since Charge is now a value, and can be
processed further.
35. Separation of Concerns
Impure function f() of type A => B can be split into
A pure function of type A => D
where D is some description of the result of f().
Description of steps or required info to execute the
steps
An impure function of type D => B
which ack as an interpreter of these descriptions.
Executor of the steps.
36. Benefits of this Separation
Pure
Impure
Function
Input Output PureInput Output
Value always allow further processing
Input No or incomplete output
Denote the end of the processing chain.
Or Miss intermediate values.
38. Exception
def failingFn(i : Int) : Int = {
val y: Int = throw new Exception("fail!");
try {
val x = 42 + 5
x + y
} catch { case e : Exception => 43 }
}
This program will fail at runtime.
39. Not Referentially Transparent
def failingFn(i : Int) : Int = {
// replace y with its value
try {
val x = 42 + 5
x + ((throw new Exception("fail!")): Int)
} catch { case e : Exception => 43 }
}
This program will not fail.
Exception can not be reasoned locally.
40. More issues with Exceptions
Exceptions are not type safe.
def map(f: String => Int) = ???
Map can not know f() can throw an exception.
This does not fit with our view of function in FP world.
41. Option data type
Two possible values
Some - holds some value.
None - No value exists.
def get(lookupKey: Int): String = {
for(entry <- entrySet) {
if(entry.key == lookupKey) { return entry.value }
}
throw new ValueNotFoundException() // or return null
}
43. Other data type to handle Errors
Optional (Java 8)
Try (scala)
Either (scala)
Maybe (Haskell)
44. Internal Side effects
Consider adding element of an array
int sum(int[] intList) {
int sum = 0;
for(int i : intList) {
sum = sum + i; // mutation
}
return sum;
}
This is acceptable inside a pure function.
45. Eliminating Internal Side effect
Use recursion
def sum(intList: List[Int]) : Int = {
if(intList.isEmpty) 0
else intList.head + sum(intList.tail)
}
Recursion is declarative.
46. Tail Recursion
Stackoverflow? Use tail recursion.
def sum(intList: List[Int], total: Int): Int = {
intList match {
case Nil => total
case head :: tail => sum(tail, total + head)
// same stack frame
}
}
sum(List(1, 2, 3), 0)
48. Consider two functions
def doubleIt(a : List[Int]) : List[Int] = {
a match { case Nil => Nil
case head :: tail => (head * 2) :: doubleIt(tail)
}}
def squareIt(a : List[Int]) : List[Int] = {
a match { case Nil => Nil
case head :: tail => (head * head) :: squareIt(tail)
}}
Example
49. Higher Abstraction
def processIt(a: List[Int], f: Int => Int) : List[Int] = {
a match { case Nil => Nil
case head :: tail => f(head) :: processIt(tail, f)
}}
Provides more opportunities of abstraction.
More opportunities for reuse.
50. Polymorphism in Types
We can do even better.
def processIt [A, B] (a: List[A], f : A => B) : List[B] = {
a match { case Nil => Nil
case head :: tail => f(head) :: processIt(tail, f)
}}
51. Map function
def map [A, B] (a: List[A], f : A => B) : List[B] = {
a match { case Nil => Nil
case head :: tail => f(head) :: map(tail, f)
}}
Part of standard library for FP languages.
52. More HOFs
Filter elements of the list.
def filter[A](x: List[A], f: A => Boolean): List[A] = ???
Similar to map but function argument result into a list
def flatMap[A, B](x: List[A], f: A => List[B]) : List[B] = ???
Fold a list into single value.
def foldLeft[A, B](x: List[A], f: (B, A) => B): B = ???
53. Function as First class citizen
First class Functions.
Pass function as arguments.
Return function as return types.
Declare function locally (like local variable).
Assign function to a variable.
Define function literals (also called as lambdas)
(x: Int) => x + 1
55. Imperative Style
Write program to find even numbers, double them and sum them up.
public int calculate() {
int[] numbers = {1, 5, 10, 9, 12};
List<Integer> doubledEvenNumbers = new ArrayList<>();
for (int number : numbers)
if(number % 2 == 0)
doubledEvenNumbers.add(number * 2);
int total = 0;
for(int even : doubledEvenNumbers)
total = total + even;
return total;
}
56. Declarative Style
Same code in declarative style with Higher order functions
List(1, 5, 10, 9, 12)
.filter(e => e % 2 == 0)
.map(e => e * 2)
.sum
Focus on what, instead of when.
Class schedule example.
59. Memoization
Result of expensive pure function can be cached and
reused again, this technique is called as Memoization.
// example of memoization in Groovy
def static sumFactors = { number ->
factorsOf(number).inject(0, {i, j -> i + j})
}
def static sumOfFactors = sumFactors.memoize()
60. Lazy evaluation
Expressions are not evaluated unless needed.
Haskell everything is evaluated lazily (as needed)
In Java and Scala streams are Lazy collections
Infinite collections can be created with lazy collection.
def fib(a: Int, b: Int): Stream[Int] =
a #:: fib(b, a + b)
val firstSeven = fib(1, 1).take(7)
firstSeven.toList // => List(1, 1, 2, 3, 5, 8, 13)
61. Parallel Programming
Independent pure functions can be executed in parallel.
Pure functions are inherently thread safe.
Declarative programming with language constructs help
parallel programming further.
val people : Array[People]
val (minors, adults) = people.par.partition(p => p.age > 18)
65. Switch cases good or bad
OO programmers consider Switch cases bad.
Conditional code. Hard to maintain
Hunt down existing cases to add new cases.
Program will misbehave if you miss to update one.
FP enhanced switch cases to pattern matching and
promote them.
What’s the Truth??
66. Types and Operations
Type against OperationsType
Operations
Infinite Type,
Finite Operations
Finite Type,
Infinite Operations
OO Solution better
FP Solution better
67. Infinite Type, Finite Operations
Implemented as Polymorphism (class hierarchy).
Easy to add new Type by Subtyping.
Difficult to add new Operations.
Finite Type, Infinite Operations
FP structures called Algebraic data types (ADTs)
Easy to add new operations using Pattern matching.
Difficult to add new Types.
68. Algebraic data type
Composite Type
Defined by one more more data constructors.
data List a = Nil | Cons x (List xs)
This is defining a list data type with 2 constructors.
69. ADT Example
Representation in scala.
interface List
class Nil extends List
class Cons(head, tail) extends List
In OO terms these constructors can be mapped to
subtypes.
70. ADT Example
ADTs have finite number of constructors or subtypes.
For list we have two constructors or subtypes
Empty list
Non empty list with head and tail.
These constructions are exhaustive and no new
subtype will ever be added.
72. OO & FP
Use ADTs and pattern matching for finite types
Use OO polymorphism for infinite types and
limited functions on those types.
Pure functions can be used in OO structure as
well.
73. Conclusion
Embrace immutability and Pure functions
Eliminate or delay the side effects
FP is not all or nothing
Choice is not OO or FP
FP can co-exists (nicely) with OO code
Functional in the small and OO in the large