This document provides an overview of functional programming concepts for object-oriented programmers. It discusses the fundamentals of FP including immutability, purity, first-class and higher-order functions, closures, and recursion. It provides examples of these concepts in languages like Lisp, F#, C#, and JavaScript. The document also compares OO and FP concepts and discusses derived FP concepts like partial application, lazy evaluation, and pattern matching.
Kotlin provides a lot of features out of the box even though those are not supported by JVM. Have you ever wondered how Kotlin does it? If yes, then this presentation is for you.
Kotlin compiler tweaks our code in such a way that, JVM can execute it. this deck goes through lots of Kotlin features and explains how it looks at runtime for JVM compatibility. Of course we are not going to look into bytecode, instead we will look into the decompiled version of the bytecode generated by Kotlin compiler.
NOTE: This was presented at DevFest Kolkata 2019.
Java 8 Stream API. A different way to process collections.David Gómez García
A look on one of the features of Java 8 hidden behind the lambdas. A different way to iterate Collections. You'll never see the Collecions the same way.
These are the slides I used on my talk at the "Tech Thursday" by Oracle in June in Madrid.
Kotlin provides a lot of features out of the box even though those are not supported by JVM. Have you ever wondered how Kotlin does it? If yes, then this presentation is for you.
Kotlin compiler tweaks our code in such a way that, JVM can execute it. this deck goes through lots of Kotlin features and explains how it looks at runtime for JVM compatibility. Of course we are not going to look into bytecode, instead we will look into the decompiled version of the bytecode generated by Kotlin compiler.
NOTE: This was presented at DevFest Kolkata 2019.
Java 8 Stream API. A different way to process collections.David Gómez García
A look on one of the features of Java 8 hidden behind the lambdas. A different way to iterate Collections. You'll never see the Collecions the same way.
These are the slides I used on my talk at the "Tech Thursday" by Oracle in June in Madrid.
Well-architected libraries for functional programming are at once immensely beautiful and practical. They are simple but extraordinarily powerful, helping users solve their problems by snapping together Lego-like building blocks, each of which has just one purpose. Yet, there is a surprising dearth of material on how developers can construct their own well-architected functional code. Many functional programming tutorials talk discuss type safety and making illegal states unrepresentable, but few speak on the subject of good functional interface design.
In this presentation, John A. De Goes takes to the stage to discuss a nebulous and underrated tool in the arsenal of every functional programmer. Called *orthogonality*, this tool allows programmers to craft the building blocks of their functional code at "right angles", so so they can be reasoned about simply and composed predictably to solve complex problems. John introduces the concept of orthogonality, looking at its geometric and algebraic origins, presents a way to measure orthogonality, and then walks through a number of interface examples, comparing non-orthogonal designs with orthogonal ones.
By the end of the session, attendees should have a newfound appreciation for how important orthogonality is to constructing good functional interfaces, and they should develop the early stages of an intuition about how to slice up a complex problem into core, single-purpose, composable building blocks.
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Chris Richardson
Higher-order functions such as map(), flatmap(), filter() and reduce() have their origins in mathematics and ancient functional programming languages such as Lisp. But today they have entered the mainstream and are available in languages such as JavaScript, Scala and Java 8. They are well on their way to becoming an essential part of every developer’s toolbox.
In this talk you will learn how these and other higher-order functions enable you to write simple, expressive and concise code that solve problems in a diverse set of domains. We will describe how you use them to process collections in Java and Scala. You will learn how functional Futures and Rx (Reactive Extensions) Observables simplify concurrent code. We will even talk about how to write big data applications in a functional style using libraries such as Scalding.
All Aboard The Scala-to-PureScript Express!John De Goes
Many Scala programmers have embraced functional programming, but the syntax and semantics of programming languages in the Haskell family remains a mystery. In this talk, Scala developers (and to some extent, Java developers) will see how the types, data structures, traits / interfaces, packages, and so forth translate into their PureScript counterparts.
What's the best way to model modular, composable effects in your purely functional program? In this presentation, I take a look at monad transformers and free monads, discuss their history, and compare how effectively they solve the problem.
Kotlin is something more than just tool that help you remove boilerplate from you code. It brings much more than just lamdas and handy syntax to your Java or Android project
The slides from the talk I gave at Oracle III #JuevesTecnológicos in Madrid.
A review of how the ParallelStreams Work in Java 8 and some considerations we must know in order to get the better performance from the concurrent data processing in #Java8
Kotlin Bytecode Generation and Runtime Performanceintelliyole
In this talk, we'll dive into the details of how various language features supported by Kotlin are translated to Java bytecode. We'll use the JMH microbenchmarking tool to study the relative performance of various constructs and to understand how we can ensure top performance of the Kotlin code that we write.
Well-architected libraries for functional programming are at once immensely beautiful and practical. They are simple but extraordinarily powerful, helping users solve their problems by snapping together Lego-like building blocks, each of which has just one purpose. Yet, there is a surprising dearth of material on how developers can construct their own well-architected functional code. Many functional programming tutorials talk discuss type safety and making illegal states unrepresentable, but few speak on the subject of good functional interface design.
In this presentation, John A. De Goes takes to the stage to discuss a nebulous and underrated tool in the arsenal of every functional programmer. Called *orthogonality*, this tool allows programmers to craft the building blocks of their functional code at "right angles", so so they can be reasoned about simply and composed predictably to solve complex problems. John introduces the concept of orthogonality, looking at its geometric and algebraic origins, presents a way to measure orthogonality, and then walks through a number of interface examples, comparing non-orthogonal designs with orthogonal ones.
By the end of the session, attendees should have a newfound appreciation for how important orthogonality is to constructing good functional interfaces, and they should develop the early stages of an intuition about how to slice up a complex problem into core, single-purpose, composable building blocks.
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Chris Richardson
Higher-order functions such as map(), flatmap(), filter() and reduce() have their origins in mathematics and ancient functional programming languages such as Lisp. But today they have entered the mainstream and are available in languages such as JavaScript, Scala and Java 8. They are well on their way to becoming an essential part of every developer’s toolbox.
In this talk you will learn how these and other higher-order functions enable you to write simple, expressive and concise code that solve problems in a diverse set of domains. We will describe how you use them to process collections in Java and Scala. You will learn how functional Futures and Rx (Reactive Extensions) Observables simplify concurrent code. We will even talk about how to write big data applications in a functional style using libraries such as Scalding.
All Aboard The Scala-to-PureScript Express!John De Goes
Many Scala programmers have embraced functional programming, but the syntax and semantics of programming languages in the Haskell family remains a mystery. In this talk, Scala developers (and to some extent, Java developers) will see how the types, data structures, traits / interfaces, packages, and so forth translate into their PureScript counterparts.
What's the best way to model modular, composable effects in your purely functional program? In this presentation, I take a look at monad transformers and free monads, discuss their history, and compare how effectively they solve the problem.
Kotlin is something more than just tool that help you remove boilerplate from you code. It brings much more than just lamdas and handy syntax to your Java or Android project
The slides from the talk I gave at Oracle III #JuevesTecnológicos in Madrid.
A review of how the ParallelStreams Work in Java 8 and some considerations we must know in order to get the better performance from the concurrent data processing in #Java8
Kotlin Bytecode Generation and Runtime Performanceintelliyole
In this talk, we'll dive into the details of how various language features supported by Kotlin are translated to Java bytecode. We'll use the JMH microbenchmarking tool to study the relative performance of various constructs and to understand how we can ensure top performance of the Kotlin code that we write.
The next version of JavaScript, ES6, is starting to arrive. Many of its features are simple enhancements to the language we already have: things like arrow functions, class syntax, and destructuring. But other features will change the way we program JavaScript, fundamentally expanding the capabilities of the language and reshaping our future codebases. In this talk we'll focus on two of these, discovering the the myriad possibilities of generators and the many tricks you can pull of with template strings.
Python is a high level language focused on readability. The Python community developed the concept of "Pythonic Code", requiring not only semantic correctness, but also conformity to universally acknowledged stylistic criteria.
A pre-requisite to write pythonic code is to write idiomatic code. Using the right idioms is a matter of acquired taste and experience, however, some idioms are quite easy to learn.
This presentation focuses on some of these idioms and other stylistic criteria:
* for vs. while
* iterators, itertools
* code conventions (space invaders)
* avoid default values bugs
* first order functions
* internal/external iterators
* substituting the switch statement
* properties, attributes, read only objects
* named tuples
* duck typings
* bits of metaprogramming
* exception management: LBYL vs. EAFP
This is the slide for what I shared in JS Group meetup, 2014, Taiwan. It covers what JavaScript could do for making the program more "functional", the benefits, price and the limitation.
C++ is a middle-level programming language developed by Bjarne Stroustrup starting in 1979 at Bell Labs. C++ runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.
This reference will take you through simple and practical approach while learning C++ Programming language.
"Are you developing or declining? Don't become an IT-dinosaur"Sigma Software
Tech Buzz, Project Management meetup, Warsaw, 2022
Krzysztof Rakowski and Paweł Rekowski, "Are you developing or declining? Don't become an IT-dinosaur"
In 18 years of learning processes facilitation, Sigma Software has delivered more than 40 solutions to fortune 500 companies, product houses, and startups. We have our own training platform Sigma Software University running 60+ training courses and consulting on e-learning. Learn how we can make training solutions and content creation more meaningful and powerful: https://bit.ly/3f4phoY
False news - false truth: tips & tricks how to avoid themSigma Software
Since the beginning of the COVID-19, the spread of information about the pandemic has been much faster than the virus itself. Facebook(link is external) labeled nearly 50 million pieces of news about COVID-19 as misinformation in April, while Twitter(link is external) marked more than 1.5 million users for spreading false information and displaying manipulative behaviors. Find out how dangerous false news is and what steps you can take to avoid them.
Modern design is crucial in today's digital environment, and this is especially true for SharePoint intranets. The design of these digital hubs is critical to user engagement and productivity enhancement. They are the cornerstone of internal collaboration and interaction within enterprises.
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.
Your Digital Assistant.
Making complex approach simple. Straightforward process saves time. No more waiting to connect with people that matter to you. Safety first is not a cliché - Securely protect information in cloud storage to prevent any third party from accessing data.
Would you rather make your visitors feel burdened by making them wait? Or choose VizMan for a stress-free experience? VizMan is an automated visitor management system that works for any industries not limited to factories, societies, government institutes, and warehouses. A new age contactless way of logging information of visitors, employees, packages, and vehicles. VizMan is a digital logbook so it deters unnecessary use of paper or space since there is no requirement of bundles of registers that is left to collect dust in a corner of a room. Visitor’s essential details, helps in scheduling meetings for visitors and employees, and assists in supervising the attendance of the employees. With VizMan, visitors don’t need to wait for hours in long queues. VizMan handles visitors with the value they deserve because we know time is important to you.
Feasible Features
One Subscription, Four Modules – Admin, Employee, Receptionist, and Gatekeeper ensures confidentiality and prevents data from being manipulated
User Friendly – can be easily used on Android, iOS, and Web Interface
Multiple Accessibility – Log in through any device from any place at any time
One app for all industries – a Visitor Management System that works for any organisation.
Stress-free Sign-up
Visitor is registered and checked-in by the Receptionist
Host gets a notification, where they opt to Approve the meeting
Host notifies the Receptionist of the end of the meeting
Visitor is checked-out by the Receptionist
Host enters notes and remarks of the meeting
Customizable Components
Scheduling Meetings – Host can invite visitors for meetings and also approve, reject and reschedule meetings
Single/Bulk invites – Invitations can be sent individually to a visitor or collectively to many visitors
VIP Visitors – Additional security of data for VIP visitors to avoid misuse of information
Courier Management – Keeps a check on deliveries like commodities being delivered in and out of establishments
Alerts & Notifications – Get notified on SMS, email, and application
Parking Management – Manage availability of parking space
Individual log-in – Every user has their own log-in id
Visitor/Meeting Analytics – Evaluate notes and remarks of the meeting stored in the system
Visitor Management System is a secure and user friendly database manager that records, filters, tracks the visitors to your organization.
"Secure Your Premises with VizMan (VMS) – Get It Now"
Designing for Privacy in Amazon Web ServicesKrzysztofKkol1
Data privacy is one of the most critical issues that businesses face. This presentation shares insights on the principles and best practices for ensuring the resilience and security of your workload.
Drawing on a real-life project from the HR industry, the various challenges will be demonstrated: data protection, self-healing, business continuity, security, and transparency of data processing. This systematized approach allowed to create a secure AWS cloud infrastructure that not only met strict compliance rules but also exceeded the client's expectations.
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.
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.
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.
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/
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.
top nidhi software solution freedownloadvrstrong314
This presentation emphasizes the importance of data security and legal compliance for Nidhi companies in India. It highlights how online Nidhi software solutions, like Vector Nidhi Software, offer advanced features tailored to these needs. Key aspects include encryption, access controls, and audit trails to ensure data security. The software complies with regulatory guidelines from the MCA and RBI and adheres to Nidhi Rules, 2014. With customizable, user-friendly interfaces and real-time features, these Nidhi software solutions enhance efficiency, support growth, and provide exceptional member services. The presentation concludes with contact information for further inquiries.
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.
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Globus
The U.S. Geological Survey (USGS) has made substantial investments in meeting evolving scientific, technical, and policy driven demands on storing, managing, and delivering data. As these demands continue to grow in complexity and scale, the USGS must continue to explore innovative solutions to improve its management, curation, sharing, delivering, and preservation approaches for large-scale research data. Supporting these needs, the USGS has partnered with the University of Chicago-Globus to research and develop advanced repository components and workflows leveraging its current investment in Globus. The primary outcome of this partnership includes the development of a prototype enterprise repository, driven by USGS Data Release requirements, through exploration and implementation of the entire suite of the Globus platform offerings, including Globus Flow, Globus Auth, Globus Transfer, and Globus Search. This presentation will provide insights into this research partnership, introduce the unique requirements and challenges being addressed and provide relevant project progress.
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.
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.
Strategies for Successful Data Migration Tools.pptxvarshanayak241
Data migration is a complex but essential task for organizations aiming to modernize their IT infrastructure and leverage new technologies. By understanding common challenges and implementing these strategies, businesses can achieve a successful migration with minimal disruption. Data Migration Tool like Ask On Data play a pivotal role in this journey, offering features that streamline the process, ensure data integrity, and maintain security. With the right approach and tools, organizations can turn the challenge of data migration into an opportunity for growth and innovation.
Globus Connect Server Deep Dive - GlobusWorld 2024Globus
We explore the Globus Connect Server (GCS) architecture and experiment with advanced configuration options and use cases. This content is targeted at system administrators who are familiar with GCS and currently operate—or are planning to operate—broader deployments at their institution.
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Anthony Dahanne
Les Buildpacks existent depuis plus de 10 ans ! D’abord, ils étaient utilisés pour détecter et construire une application avant de la déployer sur certains PaaS. Ensuite, nous avons pu créer des images Docker (OCI) avec leur dernière génération, les Cloud Native Buildpacks (CNCF en incubation). Sont-ils une bonne alternative au Dockerfile ? Que sont les buildpacks Paketo ? Quelles communautés les soutiennent et comment ?
Venez le découvrir lors de cette session ignite
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...Juraj Vysvader
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I didn't get rich from it but it did have 63K downloads (powered possible tens of thousands of websites).
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Столпы функционального программирования для адептов ООП, Николай Мозговой
1.
2. About me
Name: Nikolay Mozgovoy (FB, LinkedIn)
Developer in Sigma Software since 2013
and mentor since 2016
Teacher in KhAI (Department Of Computer
Systems, Networks And Cybersecurity)
GGJ Ukraine prizewinner (2016, 2017)
GGJ Site organizer (Kharkiv)
Media/Global hack weekend competitor
MSCSD: App builder
Caught Lisp in 2016
6. Lambda calculus
Formal system in mathematical logic for expressing
computation based on function abstraction and
application using variable binding and substitution
Turing complete
Developed by Alonzo Church in the 1930s
Notation:
λx. t[x] – function that do anything with x
λx. x^2 – x squaring function same as y=x^2
(λx y. x + y) 1 2 = (λy. 1 + y) 2 = 1 + 2 – carrying
11. Imperative code & parallel execution
BigInteger[] arr = Enumerable.Range(0, 10000)
.Select(x => new BigInteger(x)).ToArray();
BigInteger sum = 0;
foreach (var n in arr) sum += n; // OK
Parallel.For(0, arr.Length, n => sum += n); // Wrong result
// And if we apply lock it would degradate to de-facto single-threaded code
arr.AsParallel().Aggregate((a, b) => a + b); // OK
12. Functional code & parallel execution
1
3
2 43
7
10
(a, b) => a + b (a, b) => a + b
(a, b) => a + b
16. The failure of state
public void ProcessPackage(Stream package)
{
SaveMetadataInDb(package);
package.Seek(0, SeekOrigin.Begin); // !!!
/* ... */
SaveContentInSearchEngine(package);
/* ... */
LogOperation(package);
}
17. Immutability
Impossibility to change the state of the object once it was created
Immutable objects are simpler to test, and use
Truly immutable objects are always thread-safe
They help to avoid temporal coupling
Their usage is side-effect free (no defensive copies)
Identity mutability problem is avoided
They always have failure atomicity
They are much easier to cache
They prevent NULL references, which are bad
I the Lord do not change (Malachi 3:6)
18. Immutability example
; LISP
(define animals (list 'dog 'cat 'fish))
(cons 'horse animals) ; returns a new list of animals, not changing existing one
// F#
let animals = ["dog";"cat";"rat"]
let moreAnimals = List.append animals ["horse"] // returns a new list
// C#
var animals = new ReadOnlyCollection<string>(new[] { "dog", "cat", "fish" });
var moreAnimals = animals.Append("horse"); // returns new Enumerable
19. The sin of impurity
public async Task HookNextBuild(IProject project, Task buildFinished) {
var buildStarted = SyncEvents.VsBuildStarted(this.VsPid).ToTask(); // IPC
await Task.WhenAny(buildStarted, buildFinished).ConfigureAwait(false);
if (this.recentAnalysisCompletion != null) {
await this.recentAnalysisCompletion;
this.recentAnalysisCompletion = null;
this.recentCompletionTime = DateTime.Now; // Time
}
var analysisCompletion = await this.LaunchAnalysisAsync(project);
this.recentAnalysisCompletion = analysisCompletion;
}
20. Purity
The property of functions not to have side-effects and any dependence from
external state or time
Function is considered pure when:
The function always evaluates the same result value given the same
argument value(s)
Evaluation of the result does not cause any side effect
Application:
Simplifies testing
Simplifies parallel computing
Allows memoization
21. Purity example
// in F#
let inc x = x + 1 // pure function
let mutable i = 0
let badInc () = i <- i + 1 // impure function
; in LISP
(define (inc x) (+ x 1)) ; pure function
(define i 1)
(define (bad-inc!) (set! i (+ i 1)))
// in C#
Math.Pow(2, 8); // pure function
Path.GetTempFileName() ; // impure function
DateTime.Now; // impure function
22. First-class and Higher-order functions
First-class functions is a property of programming language to treat functions
as a standard datatype
Function is considered higher-order function when it does at least one of the
following:
takes one or more functions as arguments
returns a function as its result
23. First-class and Higher-order functions
// C#
// toUpper is first-class function
Func<string, string> toUpper = str => str.ToUpper();
// Select is higher-order function
new[] { "dog", "cat" }.Select(toUpper);
// F#
// fun x -> -x is first-class function & Seq.sortBy is higher-order function
[22;31;1;5;7] |> Seq.sortBy(fun x -> -x)
// >> is a higher-order function, it returns a composition of the functions
(add1 >> add1) 1 // 3
24. Recursion
Recursion is idiomatic way to perform iterations or lopping in functional
programming languages
Tail recursion usually can be recognized and optimized by a compiler
Mutual recursion may require trampoline to handle it
To iterate is human, to recurse, divine (L. Peter Deutsch)
25. Recursion example (LISP)
; mutual recursion
(define (r1 i)
(if (< i 0) 1 (r2 (- i 1))))
(define (r2 i)
(if (< i 0) 1 (r1 (- i 1))))
(r1 1000000)
; tail recursion
(define (factorial x)
(if (< x 2)
1
(* x (factorial (- x 1)))))
26. Recursion example (F#)
// mutual recursion
let rec r1 i =
if i < 0
then 1
else r2(i - 1)
and r2 i =
if i < 0
then 1
else r1(i - 1)
// tail recursion
let rec factorial x =
if x < 2
then 1
else x * factorial(x - 1)
28. Closures
A data structure containing a lambda expression, and an environment to be
used when that lambda expression is applied to arguments
Closures are used to:
bind together data and behavior (just like objects in OOP)
emulate state
emulate object system
function
environment
in which
function got
created
closure
object
29. Closure example in F# (simple and artificial)
// creates a function that raises y to a power of x
let makePowerFn x =
(fun y -> pown y x) // this lambda is a closure itself (because of reference to x)
let pow2 = makePowerFn 2
pow2 3 // 9
let pow3 = makePowerFn 3
pow3 3 // 27
30. Closure example: pure recursive data structures
type Seq = { value: int; next: (unit -> Seq) }
let rec initSeq next value : Seq = {
value = value; // return current value
next = (fun () -> initSeq next (next value)) // create a new sequence with the next value
}
let pow2Seq = initSeq (fun x -> x * 2) 2 // sequence of powers of 2
pow2Seq.value // 2
pow2Seq.next().next().value // 8
// doesn’t it look like enumerator.MoveNext().MoveNext().Current in C#?
31. Closure example: trampoline (in JavaScript)
function factorial (n) {
return n < 2
? 1
: n * factorial(n -1);
}
factorial(3); // 6
/* maximum call stack
size exceeded */
factorial(100000);
function trampoline (fn) {
while (
typeof fn === 'function') {
fn = fn();
}
return fn;
}
function factorial (n, acc = 1) {
return function () {
return (n < 2)
? acc
: factorial(n - 1, n * acc);
}
}
/* no errors */
trampoline(factorial(100000));
32. Partial application
Process of breaking a single function into a multiple ones of smaller arity
Often conflated/mixed with currying witch is a process of breaking a function of
n arguments to a chain of n functions of 1 argument each
Motivation is that very often the functions obtained by supplying some but not
all of the required arguments
papply: (((a × b) → c) × a) → (b → c) = λ(f, x). λy. f (x, y)
curry: ((a × b) → c) → (a → (b → c)) = λf. λx. λy. f (x, y)
uncurry: (a → (b → c)) → ((a × b) → c) = λf. λ(x, y). f x y
33. Partial application example (simple & artificial)
// F#
let add1 x = x + 1
// traditional definition vs application
let add1 = (+) 1
let sortAsc = List.sortWith
(fun x y -> x - y)
let sortDsc = List.sortWith
(fun x y -> y - x)
// C#
Func<string, Claim> newClaim =
value => new Claim(
"group", value, "String", “sigma.software ");
/*…*/
var groups = RetrieveGroups();
// { "Management", "Accountants“ };
var groupClaims = groups.Select(newClaim);
34. Partial application (C#)
public class Package {
private readonly IContentReader contentReader;
private readonly IChecksumGenerator checksumGenerator;
private readonly IChecksumFormatter checksumFormatter;
public Package(
string name,
IContentReader contentReader,
IChecksumGenerator checksumGenerator,
IChecksumFormatter checksumFormatter) {
this.Name = name;
this.contentReader = contentReader;
this.checksumGenerator = checksumGenerator;
this.checksumFormatter = checksumFormatter; }
public string Name { get; }
public string GetChecksumStr(Encoding encoding) =>
this.checksumFormatter.Format(
this.checksumGenerator.Generate(contentReader.Read()),
encoding);
}
public interface IContentReader {
Stream Read();
}
public interface IChecksumGenerator {
byte[] Generate(Stream dataStream);
}
public interface IChecksumFormatter {
string Format(
byte[] checksum,
Encoding encoding);
}
36. Lazy evaluation
Lazy evaluation is a way of computing in which values are not calculated until
they are required
Lazy evaluation can be accomplished:
By language itself (Haskell)
Using special data structures
The opposite of lazy evaluation called eager evaluation
Application:
Infinite data structures
Memory footprint optimization
Startup speed optimization
Often combined with memorization
37. Lazy evaluation example (simple & artificial - F#)
// F#
let lazyVal = lazy (10 * 10)
lazyVal // Lazy<int> Value is not created.
lazyVal.Force() // 100
let nat = Seq.initInfinite(fun n -> n + 1)
// seq<int> = seq [1; 2; 3; 4; ...]
Seq.skip 10 nat |> Seq.take 10
// seq<int> = seq [11; 12; 13; 14; ...]
39. Pattern matching
Language feature that allows to choose the following instruction set based on
the match of given data with one of the declared patterns:
Constants
Predicates (functions that return Boolean values)
Data type
Anything else supported by a particular language
40. Pattern matching example
// F#
let ReadFromFile reader : StreamReader) =
match reader.ReadLine() with
| null -> printfn "n"; false
| line -> printfn "%s" line;
true
// C#
public static double ComputeArea (object shape)
{
switch (shape)
{
case Square s:
return s.Side * s.Side;
case Circle c:
return c.Radius * c.Radius * Math.PI;
case Rectangle r:
return r.Height * r.Length;
default: throw new ArgumentException();
}
}
41. Concepts comparison
Goal OOP FP
Binding data & behavior Class -> Object Closure
Passing dependencies Constructor Partial application
Decoupling from concrete
implementation
Interface Function signature
Controlling execution flow Switch statement Pattern matching
42. Summary
Fundamentals concepts:
Immutability
Simplifies reasoning & testing; Increases scalability & reliability;
Purity
Simplifies reasoning and testing; Increases scalability & reliability;
First-class, higher-order functions
Closures
Functional way to bind data and behavior
Partial application
Functional way to have constructors
Lazy evaluation
Speed ups initialization
43. What’s next?
State management
The problem of state
Approaches of managing the state and side-effects
Continuations
Promises
Monads
FRP
44. Books
Structure and interpretation of computer programs
MIT course 6.037
Introduction to Functional Programming
Cambridge CS department
Hackers and painters
Google Play Books
Amazon
45. Articles
Rich Hickey – Simple made Easy
https://github.com/matthiasn/talk-
transcripts/blob/master/Hickey_Rich/SimpleMadeEasy.md
Vladimir Khorikov - Functional C#
https://github.com/vkhorikov/CSharpFunctionalExtensions
Robert Martin – FP vs OO
http://blog.cleancoder.com/uncle-bob/2014/11/24/FPvsOO.html
Why Functional Programming matters
https://www.cs.kent.ac.uk/people/staff/dat/miranda/whyfp90.pdf
Me - LISP: back to the future (a tribute to 60th anniversary):
https://sigma.software/about/media/lisp-back-future-tribute-60th-
anniversary
Любопытно что функциональная парадигма появилась так давно. Раньше чем структурное и чем GOTO стал considered harmful.
LISP – Первый функциональный и второй высокоуровневый язык –после FORTRAN, до сих пор наголову превосходит большинство языков общего назначения по своим возможностям.Первый язык с IF, garbage collection, функции как базовый тип данных, возможности метапрограммирования
Что интересно что Джон Маккарти (автор LISP и термина Искусственный интеллект) сам признавал что не понял работу Алонзо Чёрча
Выписал основные языки. Тут важно отметить 2 семейства которые повлияли на все остальные: LISP & ML
Интерес к древней функциональной парадигме, в значительной мере пропорционален изменению наших вычислительных возможностей.
Ядер становится всё больше при том что тактовая частота не сильно поменялась со средины нулевых
Заметим, что кроме центрального процессора мы имеет графический, который отличается наличием ТЫСЯЧ ядер, которые могут выполнять параллельные вычисления (пусть и узкоспециализированные)
И вот последний важный момент связанный с ограничениями железа, цена на оперативную память радикально (экспоненциально), аргумент против «более прожорливых» функциональных языков более не актуален.
Сразу к примеру, почему императивный подход оказался нерабочим в новых условиях
Каждая операция не зависит друг от друга, может выполнятся поралельно
Прежде чем перейти к основным понятиям функционального программирования интересно напомнить ОО
Прежде чем перейти к основным понятиям функционального программирования интересно напомнить ОО/ Мне кажется очень удобно подойти к этому вопросу также как мы подходим к ОО.
Здесть тоже можно выделить 4 принципа. При этом что важно все присущие ОО свойства кроме наследования остаются в силе и в рамках ФП
То что на первый взгляд кажется ограничением, в реальности крайне полезное свойство избавляющее разработчика от множества дефектов
Здесь возникает вопрос, не расточительно ли создавать каждый раз новые объекты, вместо того что бы изменять существующие?
Опять совершенное реальный пример, с реального проекта. Очень важная функция совершенно не тестируема, а результат её работы не воспроизводим.
Она явным образом совершает 2 вещи которые нарушают свойство её «чистоты»:
Ждёт сигналов от других процессов
Зависит от реального времени (DateTime.Now)
Кошерный код в данном контексте приобретает весьма определённое значение
Кошерный код в данном контексте приобретает весьма определённое значение
Помним, что в функциональный языках нельзя менять состояние объектов. По этому цикл for int i = 0; i<10;i++ не катит
Очень похоже на enumerator в C#, но здесь состояние только эмулируется. Всё это чистые функции
Элегантный костыль для языков с фиксированным стеком вызовов
Керрирование названо в честь Хаскеля Карри
Реальный пример, реального проекта. Чексумма вычисляется только при необходимости
Но причём тут частично применение?
Реальный пример, реального проекта. Чексумма вычисляется только при необходимости
Но причём тут частично применение?
Реальный пример, реального проекта. Чексумма вычисляется только при необходимости
Но причём тут частично применение?
Если всё так похоже почему так получилось что мы пользуем ООП?
Что важно. Это парадигма, это не конкретный язык. Как минимум принципам неизменяемости и чистоты вы можете следовать в любом языке
Introduction to Functional Programming (1996/7) - John Harrison