This document provides an introduction to functional programming concepts for Java developers. It discusses some drawbacks of object-oriented programming, such as difficulties achieving concurrency and reusability. Functional programming is presented as an alternative with advantages like being more declarative, enabling easier concurrency through immutable functions, providing more coarse-grained abstractions, and improved code reuse through function composition. The document then covers key FP concepts like higher-order functions, lazy evaluation, and common data transformations. It also discusses how design patterns and caching are approached differently in FP.
This slide notes are more than 10 years old of my teacher Mr Karim Zebari. He uses a brilliant simple language to explain programming principles step by step.
Overview of Groovy language features and lead to Functional Programming in Groovy. As this is a code along session backed by this presentation, code examples are not include here as I code them live.
This slide notes are more than 10 years old of my teacher Mr Karim Zebari. He uses a brilliant simple language to explain programming principles step by step.
Overview of Groovy language features and lead to Functional Programming in Groovy. As this is a code along session backed by this presentation, code examples are not include here as I code them live.
This presentation will introduce you to programming languages that support different programming paradigms and to give you the knowledge of basic concepts and techniques that will allow them to differentiate between various programming paradigms.
Course: Programming Languages and Paradigms:
A brief introduction to imperative programming principles: history, von neumann, BNF, variables (r-values, l-values), modifiable data structures, order of evaluation, static and dynamic scopes, referencing environments, call by value, control flow (sequencing, selection, iteration), ...
To make this comparison we need to first consider the problem that both approaches help us to solve. When programming any system you are essentially dealing with data and the code that changes that data. These two fundamental aspects of programming are handled quite differently in procedural systems compared with object oriented systems, and these differences require different strategies in how we think about writing code.
This presentation will introduce you to programming languages that support different programming paradigms and to give you the knowledge of basic concepts and techniques that will allow them to differentiate between various programming paradigms.
Course: Programming Languages and Paradigms:
A brief introduction to imperative programming principles: history, von neumann, BNF, variables (r-values, l-values), modifiable data structures, order of evaluation, static and dynamic scopes, referencing environments, call by value, control flow (sequencing, selection, iteration), ...
To make this comparison we need to first consider the problem that both approaches help us to solve. When programming any system you are essentially dealing with data and the code that changes that data. These two fundamental aspects of programming are handled quite differently in procedural systems compared with object oriented systems, and these differences require different strategies in how we think about writing code.
Designing function families and bundles with java's behaviors parameterisatio...Alain Lompo
User requirements are sinking sands: should we care or should we leave it to the business managers? Java’8 behaviours parameterization and lambdas help shift paradigms from business to design: here the audience will learn how to efficiently deal with the issue and make their customers smile.
The course aims to provide you with an understanding of the fundamental concepts involved in object-oriented programming (object, class, protocol, hierarchy, inheritance, encapsulation, polymorphism and collaboration).
The programming language you will use is Java. However, the purpose of the course is not to teach you the minutiae of the Java language, but rather to teach you fundamental object-oriented programming concepts and skills that will be transferable to any object¬ oriented language
PHP Frameworks: I want to break free (IPC Berlin 2024)Ralf Eggert
In this presentation, we examine the challenges and limitations of relying too heavily on PHP frameworks in web development. We discuss the history of PHP and its frameworks to understand how this dependence has evolved. The focus will be on providing concrete tips and strategies to reduce reliance on these frameworks, based on real-world examples and practical considerations. The goal is to equip developers with the skills and knowledge to create more flexible and future-proof web applications. We'll explore the importance of maintaining autonomy in a rapidly changing tech landscape and how to make informed decisions in PHP development.
This talk is aimed at encouraging a more independent approach to using PHP frameworks, moving towards a more flexible and future-proof approach to PHP development.
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
Elevating Tactical DDD Patterns Through Object CalisthenicsDorra BARTAGUIZ
After immersing yourself in the blue book and its red counterpart, attending DDD-focused conferences, and applying tactical patterns, you're left with a crucial question: How do I ensure my design is effective? Tactical patterns within Domain-Driven Design (DDD) serve as guiding principles for creating clear and manageable domain models. However, achieving success with these patterns requires additional guidance. Interestingly, we've observed that a set of constraints initially designed for training purposes remarkably aligns with effective pattern implementation, offering a more ‘mechanical’ approach. Let's explore together how Object Calisthenics can elevate the design of your tactical DDD patterns, offering concrete help for those venturing into DDD for the first time!
Welocme to ViralQR, your best QR code generator.ViralQR
Welcome to ViralQR, your best QR code generator available on the market!
At ViralQR, we design static and dynamic QR codes. Our mission is to make business operations easier and customer engagement more powerful through the use of QR technology. Be it a small-scale business or a huge enterprise, our easy-to-use platform provides multiple choices that can be tailored according to your company's branding and marketing strategies.
Our Vision
We are here to make the process of creating QR codes easy and smooth, thus enhancing customer interaction and making business more fluid. We very strongly believe in the ability of QR codes to change the world for businesses in their interaction with customers and are set on making that technology accessible and usable far and wide.
Our Achievements
Ever since its inception, we have successfully served many clients by offering QR codes in their marketing, service delivery, and collection of feedback across various industries. Our platform has been recognized for its ease of use and amazing features, which helped a business to make QR codes.
Our Services
At ViralQR, here is a comprehensive suite of services that caters to your very needs:
Static QR Codes: Create free static QR codes. These QR codes are able to store significant information such as URLs, vCards, plain text, emails and SMS, Wi-Fi credentials, and Bitcoin addresses.
Dynamic QR codes: These also have all the advanced features but are subscription-based. They can directly link to PDF files, images, micro-landing pages, social accounts, review forms, business pages, and applications. In addition, they can be branded with CTAs, frames, patterns, colors, and logos to enhance your branding.
Pricing and Packages
Additionally, there is a 14-day free offer to ViralQR, which is an exceptional opportunity for new users to take a feel of this platform. One can easily subscribe from there and experience the full dynamic of using QR codes. The subscription plans are not only meant for business; they are priced very flexibly so that literally every business could afford to benefit from our service.
Why choose us?
ViralQR will provide services for marketing, advertising, catering, retail, and the like. The QR codes can be posted on fliers, packaging, merchandise, and banners, as well as to substitute for cash and cards in a restaurant or coffee shop. With QR codes integrated into your business, improve customer engagement and streamline operations.
Comprehensive Analytics
Subscribers of ViralQR receive detailed analytics and tracking tools in light of having a view of the core values of QR code performance. Our analytics dashboard shows aggregate views and unique views, as well as detailed information about each impression, including time, device, browser, and estimated location by city and country.
So, thank you for choosing ViralQR; we have an offer of nothing but the best in terms of QR code services to meet business diversity!
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™UiPathCommunity
In questo evento online gratuito, organizzato dalla Community Italiana di UiPath, potrai esplorare le nuove funzionalità di Autopilot, il tool che integra l'Intelligenza Artificiale nei processi di sviluppo e utilizzo delle Automazioni.
📕 Vedremo insieme alcuni esempi dell'utilizzo di Autopilot in diversi tool della Suite UiPath:
Autopilot per Studio Web
Autopilot per Studio
Autopilot per Apps
Clipboard AI
GenAI applicata alla Document Understanding
👨🏫👨💻 Speakers:
Stefano Negro, UiPath MVPx3, RPA Tech Lead @ BSP Consultant
Flavio Martinelli, UiPath MVP 2023, Technical Account Manager @UiPath
Andrei Tasca, RPA Solutions Team Lead @NTT Data
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
Securing your Kubernetes cluster_ a step-by-step guide to success !
Introduction to functional programming
1. A brief introduction/summarization about functional
programming (FP) and paradigm shift of software
engineering from OOP to FP for Java developers
Thang Ngoc Mai
Introduction to
Functional Programming
KMS Technology
2. 2
OOP has served us well but it has drawbacks
☐ Hard to Achieve Concurrency
Imperative paradigm does not fit very well with concurrency
need as it is based on changing state and ordered steps.
It is also hard to avoid the evil shared mutability in OOP code.
As of now, multithread programming, requiring synchronized
access, is the assembly language of concurrency.
☐ Less Re-Usable Abstractions
OOP model is hardly usable widely because every
object model is so unique for each
situation/problem. This makes modularity of OOP
less attractive
Also it is hard to do it right in OOP design because
there can be so many candidate models to solve a
same problem. And even in case we can make it
right, later we still might have to throw them away
when business change. And still we can hardly re-
use them in other contexts.
How many times you have developed the
Employee/Customer classes in your career?
It is time to look out for better alternatives.
☐ Imperative
Intent of program can be hard to
understand with imperative code
because the code is more about how
and not about what.
3. 3
Why FP?
☐ Declarative
Focus on results, not steps
Result in expressive yet concise code.
And thus intent of code is easier to
understand
☐ Concurrency
This is the notable reason why FP gains
widespread interest recently.
Functions are pure (no side effect) thus
are always safe for concurrency. In
context where mutating state is not
avoidable, Actor model and Software
transactional memory (STM) come to
rescue.
☐ Coarse-grained Abstractions
FP abstract more details from developers such as
iteration/caching/concurrency/lazy evaluation.
These mundane details are handled by languages and
runtimes, giving developers more time to solve real
problems.
The more low-level details a programming language
can handle for you, the fewer places that leave you to
introduce bugs and complexity.
☐ Code Reuse via Composition
FP makes code understandable by
minimizing moving parts (changes)
A function should be side effect free thus
has no dependencies and therefore easier
to reuse (better modularity).
4. 4
We Should Have FP in Our Toolbox
☐ Side Effects
The biggest advantage of FP and also the biggest
disadvantage of FP is side effect since we do need
side effect in software (etc. IO)
☐ No Panacea
Both OOP and FP are tools, not panaceas. Each
has advantages and disadvantages. Let’s have a
bigger toolbox and a broadened perspective.
5. 5
So What is FP?
☐ FP is More a Mindset
FP is more a mindset than languages or tools. You can even code functionally in Java
although syntax will be cumbersome. First point is when developers think functionally,
they should focus on results instead steps to solve a problem.
Secondly, because FP represents problems differently with different building blocks,
developers have to adapt with these building blocks and how to glue them together.
Thus FP requires developers to think in a different way that they do in OOP
☐ Programming with Functions
Functional program is just a function. Thus functional applications or features are composed by
small functions together.
In OOP, the units of reuse are classes thus it encourages developers to create unique data
structures. In contrast, function is the building block in FP. And thus, FP instead prefers a few key
data structures (list, set, map) with highly optimized operations on those data structures. These
differences are subtle but powerful since it simplify and enable better code reuse mechanism.
“Functional programming is a programming
paradigm that treats computation as the
evaluation of mathematical functions and
avoids state and mutable data”
6. 6
Concepts in FP
From here I will briefly introduce each common concept in functional programming. Below is list of them.
Higher Order Function
First Class Function
Currying
Partial Application
Memoization
Lazy Evaluation
Common Transformations in FP: filter, map, and reduce
Dispatch in FP
Recursive Looping
Monad
7. 7
Higher Order Function
Higher order functions are functions which can either take other functions as arguments or return them as results.
☐ Groovy Example
def makeCounter() {
def very_local_variable = 0
return { return very_local_variable += 1 }
}
c1 = makeCounter()
c1()
c1()
c1()
c2 = makeCounter()
makeCounter() is a not a normal function. It
is a higher order function which returns a
another function (actually a closure here)
which later will be assigned to c1 and c2
variables. Note that in Groovy, anything
inside curly braces is a code block.Invoke c1() three times and receive
1,2,3 respectively.
Invoke makeCounter() again to obtain
a new counter function which starts at
1
8. 8
First Class Function
Functional languages treat function as first class citizen
With above definition, you can easily see that function is not (yet) a first class citizen in Java. At least until Java 8 is
released early next year with support for Lambda Expressions.
☐ What is First Class Citizen??
☐ What Does All that Mean?
First class function allows uses of functions in unexpected
ways and force thinking about solutions differently. In OOP,
we think about classes and how they are structured and
interact with each other. In FP, we think about functions
and how to create them (even at runtime) and compose
them together.
In any language, a first class citizen is an entity that can
be:
Stored in variables and data structures
Constructed at run-time
Passed as a parameter
Returned from a subroutine
Assigned into a variable
9. 9
Currying Currying is a technique of transforming a
function that takes multiple arguments in such
a way that it can be called as a chain of
functions, each with a single argument.
☐ How Does It look?
Given , currying produces:
.
☐ JRuby Examples
product = ->(x,y,z){x * y * z}
product.(2,4,6)
product.curry[2][4][6]
We create a lambda here (assigned to product) which
take three parameters and multiple them together and
return result
product can be invoked either in a
normal way or in a curried way like
this to produce a same result of 48
product = ->(x,y){x * y}
double = product.curry[2]
quadrate = product.curry[4]
octate = product.curry[8]
Again, create a lambda
But this time, we use currying to create
three different functions based on original
one. This demonstrates idea about currying
acts as a factory for functions
10. 10
Partial Application
☐ Definition
Partial application (or partial function application) refers to the process of fixing a number of
arguments to a function, producing another function of smaller arity.
Note that partial application is different with currying but these two terms are often used
interchangeably
☐ JRuby Example
binary_operator = ->(operator, x, y){operator[x,y]}
adder = ->(x,y){x + y}
product = ->(x,y){x * y}
# Use curry() for partial application
curried_product = binary_operator.curry[product]
curried_adder = binary_operator.curry[adder]
# Note Ruby’s beautiful syntax
curried_product1 = binary_operator.curry[:*]
curried_adder1 = binary_operator.curry[:+]
# returns 30
curried_product.(5,6)
# returns 11
curried_adder.(5,6)
binary_operator is a higher order
function which take a binary function
and apply it to the other parameters.
We have two binary operators
adder and product.
We use curry in JRuby to partially
apply adder and product to
binary_operator function and yielding
two functions.
11. 11
Partial Application
☐ Another Example
composer = ->(f,g,x){f.(g.(x))}
product = ->(x,y){x * y}
double = product.curry[2]
quadrate = product.curry[4]
octate = composer.curry[double, quadrate]
# Returns 800
octate.(100)
We define a function to combine
functions together.
Then use partial application to yield a new
function from two original ones.
12. 12
OOP Design Patterns in FP
Neal Ford has three articles on this topic. According to those, in the functional-programming world, traditional design
patterns generally manifest in one of three ways:
The pattern is absorbed by the language.
The pattern solution still exists in the functional paradigm, but the implementation details differ.
The solution is implemented using capabilities other languages or paradigms lack. (For example, many solutions
that use metaprogramming are clean and elegant — and they're not possible in Java.)
I just try to summarize his articles here into a few points below.
Command pattern is no longer needed in FP
Currying is used as Function Factory and it is supported at language level
With first class function, Template Method and Strategy, Adapter become much simpler
With presence of memorization (Groovy and Clojure), FlyWeight is not necessary any more. This is an example of
offloading mundane tasks to language and runtimes
Operator overloading and meta-programming makes Interpreter become much simpler and more powerful
Language level feature like Pattern matching in Scala make Visitor pattern cumbersome and almost no longer
needed (Martin et al. chapter 15).
13. 13
Caching and Memoization
In OOP languages, caching generally happen at object level and developers mush manage it themselves. Many functional
programming languages build caching in function level via memorization. This is also an example of how FP strives to
minimize moving parts by building reusable mechanism into the runtime. Again the idea is all about buying more time for
developers to focus on their own tasks. Memorization is all about asking runtime to perform caching at function level
(Note that a non-pure function should not be cached as it is a source of bugs). Let’s take a look at a sample API for
memorization from Groovy to see how handy they are.
memoizeAtMost(max) call which caches a maximum number of invocations
memoizeAtLeast(min) call which keeps at least a certain number of invocation results
and memoizeBetween(min, max) which keeps a range results (between a minimum and a maximum)
def plus = { a, b -> sleep 1000; a + b }.memoize()
assert plus(1, 2) == 3 // after 1000ms
assert plus(1, 2) == 3 // return immediately
assert plus(2, 2) == 4 // after 1000ms
assert plus(2, 2) == 4 // return immediately
// other forms:
//at least 10 invocations cached
def plusAtLeast = { ... }.memoizeAtLeast(10)
// at most 10 invocations cached
def plusAtMost = { ... }.memoizeAtMost(10)
// between 10 and 20 invocations cached
def plusAtLeast = { ... }.memoizeBetween(10, 20)
14. 14
Lazy Evaluation
☐ What is It?
Lazy evaluation is deferral of expression
evaluation for as long as possible
It is a feature of many functional
programming languages
☐ Why Lazy Evaluation matter?
Defer expensive calculation until they are
absolutely needed
Can create infinite collections which is not
possible with eager collections
Reduced storage size as we don’t have to store
everything upfront
Allow to generate more efficient code
15. 15
Common Transformations
Object-oriented languages encourage us to create class-specific methods, and you can capture recurring patterns for later reuse. Functional
languages help us to achieve reuse by encouraging the application of common transformations to data structures, with higher-order functions to
customize the operation for specific instances. Below are common transformations in FP which have different names in different languages. Note
that there are inconsistencies of terminology for same transformation in different languages. Here I summarize some common transformations
which are well noted in article #16 in Neal Ford’s functional thinking series.
☐ map and collect
A transformation which invokes a function on each
element from a list then creates a new list containing
values return by that function
☐ filter & findAll &select
A transformation which invokes an input predicate on
each element from a list to determine which values will
be included in the return list.
A predicate is a function which only returns true or
false.
☐ Reduce & inject & reduceLeft
Combine all elements by applying a specified binary
operation
18. 18
Reduce & inject & reduceLeft
# Returns result: 55
(1..10).reduce(:+)
def list = 1..10
// return result: 55
list.inject {x,y -> x + y}
☐ JRuby ☐ Groovy
val list = 1 until 11
//Return result: 55
list.reduceLeft((a,b) => a + b)
; Returns result: 55
(reduce + (range 1 11))
☐ Clojure
☐ Scala
19. 19
pmap in Clojure
As we are familiar with map already in previous page, let's examine pmap (paralel) in Clojure which will execute mappings
concurrently (and also semi-lazily). Presence of building block such as pmap demonstrates idea (yes, again) how language
and runtimes can handle mundane tasks for developers so that we will have more time to focus on resolving real
problems.
I left out implementation of fetch-url since it is not needed to demonstrate the idea. Let’s suppose we already had fetch-
url function implemented somewhere. The code in this example executes fetching content from each website in parallel.
If you are already familiar with Execution Framework in Java (I assume you are) then you can see that how cumbersome it
is the equivalent code in Java to do the same thing here with all Callable, Future, Executor, ExecutorService along the way.
Let language and runtimes do these things for us. Here I want to mention a quote from Dean Wampler:
“Multithreaded programming, requiring synchronized access to shared, mutable state, is
the assembly language of concurrency”
; Having a list of url to fetch
(def url-list (list "www.url1.com" "www.url2.com" "www.url3.com"))
; Returns
(pmap #(fetch-url %) url-list)
☐ pmap Contrived Simple Stupid Example
20. 20
Parallel Collections in Scala
Thanks to Nhan Tran who gave me an example about parallel collections in Scala which is similar to the pmap example
above in Clojure but with different approach. Instead of concurrent function, concurrency is built inside parallel
collections like ParArray, ParVector, ParHashMap etc. Let’s take a look at an example.
Above example is from scala’s documentation on parallel collections in following link.
http://docs.scala-lang.org/overviews/parallel-collections/overview.html
// Create a list
val list = (1 to 10000).toList
// Convert it to a parallel list with par() then call map to transform to
// a new list by adding 42 to each element concurrently.
list.par.map(_ + 42)
21. 21
Dispatch in FP
Working on Java, we depend on if and switch statements for dispatch. FP provides us some alternatives for the same
purpose. Groovy offers a switch statement which accepts dynamic types while Scala’s flavor is pattern matching. And
Clojure has multi methods – a functional polymorphism which is equivalent to polymorphism in OOP with fewer
limitations. Let’s take a look.
☐ Multi Methods Example
(defmulti auto-answer (fn [caller] (caller :is-a)))
(defmethod auto-answer :girl [caller] "I love you")
(defmethod auto-answer :friend [caller] "What's up")
(defmethod auto-answer :colleague [caller] "How are you")
(defmethod auto-answer :boss [caller] "Yes sir, sure")
(defmethod auto-answer :default [caller] "mmm")
=> (auto-answer {:is-a :friend})
"What's up"
=> (auto-answer {:is-a :colleague})
"How are you"
=> (auto-answer {:is-a :girl})
"I Love You"
In Clojure, a dispatch function is
defined by defmuti. Any
invocation of auto-answer will
pass parameters to this function.
Based on value retuned by
dispatch function, execution will
be dispatched to appropriate
method. This is similar with
behavior we have in OOP’s
polymorphism
All these new dispatch mechanisms are
powerful and we don’t need to depend on
design patterns like Factory but they
requires a change in the way we think as it
is part of thinking functionally
22. 22
Recursive Looping
At this point, you might not be surprised any more to know that functional approach does not favor use of
constructs like ‘for’ and ‘while’ for looping and iteration. Instead, Looping and iteration are replaced /
implemented by recursive function calls (Rich Hickey)
☐ What Languages Support Tail Recursion?
Clojure has ‘recur’ and 'trampoline’ as special operators to support tail call optimization
(TCO).
Scala support tail call optimization at language level.
Groovy does not (yet) support TCO. However it has trampoline.
JRuby does not support TCO yet.
Tail call and tail recursion is a subproject to introduce TCO for the JVM and Hopefully JDK 1.8
will come with TCO support. That would enable TCO for all languages on the JVM.
☐ So What about Stack Space Problem?
Recursion is nice but it has a problem with stack space consumption. Recursive function can easily
result in a stack overflow exception with large enough recursive calls.
Many languages guarantee that function calls made in tail position do not consume stack space and
thus recursive loops utilize constant space. Note: Same optimization cannot be achieved with head
recursion.
With such tail recursion optimization, we have peace in mind when writing recursive function.
23. 23
Monad
Probably Monad is the most difficult to understand concept in functional programming. It could take you 3 days or
probably months to understand. However, the good news is you don’t need to understand Monad to apply FP in your
daily assignments. Once you get used to functional programming, I believe soon you will understand Monad. I would
recommend following articles for getting started:
Understanding monads
http://en.wikibooks.org/w/index.php?title=Haskell/Understanding_monads&oldid=933545
Don’t fear monads
http://channel9.msdn.com/Shows/Going+Deep/Brian-Beckman-Dont-fear-the-Monads
In case you need more articles, here is a consolidated list of all tutorials about monads
http://www.haskell.org/haskellwiki/Monad_tutorials_timeline
24. 24
FP is On The Rise
☐ Results over Steps
Java eased our interaction with memory
management; functional programming languages
eased our focus on how steps should be done.
Examples are details on concurrency, iteration,
transformations and caching can be handled by
languages and runtime.
The more low-level details a programming language
can handle for you, the fewer places that leave you
to introduce bugs and complexity
☐ Think Functionally
FP offers new and powerful tools which can help solve tricky problems in
elegant ways. Developers need to adapt to functional thinking to make use
of them effectively.
So start thinking about resolving problem with how, wrapping function in
list/tree/hash, manipulating array and tree with functions and so on.
☐ Minimize Moving Parts
OOP makes code understandable by
encapsulating moving parts. FP makes code
more understandable by minimizing
moving parts. Immutability is one primary
reason why FP shines in concurrency.
25. 25
Recommendation on Where to Start
1. If you are a Java developer and you are new to FP then first go through 20 articles from Neal Ford in his functional
thinking series. These series of articles would have convinced you on how elegant and powerful FP is. I like Neal
Ford’s series because it discuss in detail on how FP can help us (developers) to work more efficiently. The series is
also very readable.
2. Then, you might want to start with the book “Functional Java Programming for Java Developers” to have a fair grip
on Data structures / Algorithm / Concurrency in FP.
3. You then can start to learn and use a functional language seriously like Scala or Groovy or Clojure. I was started
with Clojure (and Clojure is my favorite) but I would recommend Scala or Groovy as I think getting familiar to
Clojure syntax could distract your focus on FP concepts.
4. From that point, you might want to tackle the most difficult topic in FP: Monad. Notes: You should not start to
learn FP with Monads. That would slow your learning process.
26. 26
References
1. Functional Thinking 20 articles series – Neal Ford - http://www.ibm.com/developerworks/java/library/j-
ft1/index.html
2. Dean Wampler 2011. Functional Java Programming for Java Developers
3. Why Functional Programming Matters - http://www.cs.kent.ac.uk/people/staff/dat/miranda/whyfp90.pdf
4. Object Oriented Programming Oversold - http://www.geocities.com/tablizer/oopbad.htm
5. Martin, F., 2010. Domain Specific Languages. Addison Wesley
6. Venkat, S., 2011. Programming Concurrency on the JVM
7. Functional Programming - http://en.wikipedia.org/wiki/Functional_programming
8. Don’t fear monads: http://channel9.msdn.com/Shows/Going+Deep/Brian-Beckman-Dont-fear-the-Monads
9. State of Lambda: Libraries Edition: http://cr.openjdk.java.net/~briangoetz/lambda/collections-overview.html
10.Martin at el. 2011. Programming in Scala 2nd edition. Artima Inc;