What did functional programming ever do for us (software engineers)? An overview of advantages of functional programming, with code examples in Scala. See recorded presentation at https://youtu.be/glDudJ3fqLk
Value Objects, Full Throttle (to be updated for spring TC39 meetings)Brendan Eich
Slides I prepared for the 29 January 2014 Ecma TC39 meeting, on Value Objects in JS, an ES7 proposal -- this one shotgunned the roadmap-space of declarative syntax, to find the right amount per TC39 (nearly zero, turns out).
Debugging and Profiling C++ Template MetaprogramsPlatonov Sergey
Template metaprogramming is an emerging new direction in C++ programming for executing algorithms in compilation time. Despite all of its already proven benefits and numerous successful applications, it is yet to be accepted in industrial projects. One reason is the lack of professional software tools supporting the development of template metaprograms. A strong analogue exists between traditional runtime programs and compile-time metaprograms. This connection presents the possibility for creating development tools similar to those already used when writing runtime programs. This paper introduces Templight, a debugging framework that reveals the steps executed by the compiler during the compilation of C++ programs with templates. Templight’s features include following the instantiation chain, setting breakpoints, and inspecting metaprogram information. This framework aims to take a step forward to help template metaprogramming become more accepted in the software industry.
Some notes about programming in Scala: it covers Scala syntax and semantics, programming techniques, idioms, patterns. Many Scala features are introduced, from basic to intermediate and advanced. These are not introductory notes, but they assume a working knowledge with some other programming language (Java, C#, C++), object-oriented programming (OOP) concepts, and functional programming (FP) concepts.
Applying Compiler Techniques to Iterate At Blazing SpeedPascal-Louis Perez
In this session, we will present real life applications of compiler techniques helping kaChing achieve ultra confidence and power its incredible 5 minutes commit-to-production cycle [1]. We'll talk about idempotency analysis [2], dependency detection, on the fly optimisations, automatic memoization [3], type unification [4] and more! This talk is not suitable for the faint-hearted... If you want to dive deep, learn about advanced JVM topics, devoure bytecode and see first hand applications of theoretical computer science, join us.
[1] http://eng.kaching.com/2010/05/deployment-infrastructure-for.html
[2] http://en.wikipedia.org/wiki/Idempotence
[3] http://en.wikipedia.org/wiki/Memoization
[4] http://eng.kaching.com/2009/10/unifying-type-parameters-in-java.html
With Ateji PX, no need to be specialized in Java threads, parallel programming on multicore, GPU, cloud and grid can be as simple as inserting a || operator in the source code.
Value Objects, Full Throttle (to be updated for spring TC39 meetings)Brendan Eich
Slides I prepared for the 29 January 2014 Ecma TC39 meeting, on Value Objects in JS, an ES7 proposal -- this one shotgunned the roadmap-space of declarative syntax, to find the right amount per TC39 (nearly zero, turns out).
Debugging and Profiling C++ Template MetaprogramsPlatonov Sergey
Template metaprogramming is an emerging new direction in C++ programming for executing algorithms in compilation time. Despite all of its already proven benefits and numerous successful applications, it is yet to be accepted in industrial projects. One reason is the lack of professional software tools supporting the development of template metaprograms. A strong analogue exists between traditional runtime programs and compile-time metaprograms. This connection presents the possibility for creating development tools similar to those already used when writing runtime programs. This paper introduces Templight, a debugging framework that reveals the steps executed by the compiler during the compilation of C++ programs with templates. Templight’s features include following the instantiation chain, setting breakpoints, and inspecting metaprogram information. This framework aims to take a step forward to help template metaprogramming become more accepted in the software industry.
Some notes about programming in Scala: it covers Scala syntax and semantics, programming techniques, idioms, patterns. Many Scala features are introduced, from basic to intermediate and advanced. These are not introductory notes, but they assume a working knowledge with some other programming language (Java, C#, C++), object-oriented programming (OOP) concepts, and functional programming (FP) concepts.
Applying Compiler Techniques to Iterate At Blazing SpeedPascal-Louis Perez
In this session, we will present real life applications of compiler techniques helping kaChing achieve ultra confidence and power its incredible 5 minutes commit-to-production cycle [1]. We'll talk about idempotency analysis [2], dependency detection, on the fly optimisations, automatic memoization [3], type unification [4] and more! This talk is not suitable for the faint-hearted... If you want to dive deep, learn about advanced JVM topics, devoure bytecode and see first hand applications of theoretical computer science, join us.
[1] http://eng.kaching.com/2010/05/deployment-infrastructure-for.html
[2] http://en.wikipedia.org/wiki/Idempotence
[3] http://en.wikipedia.org/wiki/Memoization
[4] http://eng.kaching.com/2009/10/unifying-type-parameters-in-java.html
With Ateji PX, no need to be specialized in Java threads, parallel programming on multicore, GPU, cloud and grid can be as simple as inserting a || operator in the source code.
Automatic Task-based Code Generation for High Performance DSELJoel Falcou
Providing high level tools for parallel programming while sustaining a high level of performance has been a challenge that techniques like Domain Specific Embedded Languages try to solve. In previous works, we investigated the design of such a DSEL – NT2 – providing a Matlab -like syntax for parallel numerical computations inside a C++ library.
Main issues addressed here is how liimtaions of classical DSEL generation and multithreaded code generation can be overcome.
This is an introductory SCALA workshop for a JAVA developer. Hence, we're going to explore 'functional' side of the language. SCALA is 50% OOP (Object-Oriented-Programming) and 50% FP (Functional-Programming). Main principles of FP are discussed, such as: tail-recursion, currying, pure-functions, lazy evaluation etc.) along with some examples in code.
We look at the basic keywords and constructs in SCALA.
In the end SCALA tools which are helpful for developers are listed.
Shape Safety in Tensor Programming is Easy for a Theorem Prover -SBTB 2021Peng Cheng
We present shapesafe (https://github.com/tribbloid/shapesafe) - the most comprehensive compile-time verifier for scala linear algebra - by only exploiting scala's type system as a theorem prover. This new paradigm allows type-level tensor computations, even those as complex as composite neural network blocks, to be rewritten, simplified and verified while being written. We will talk about its design and limitations, and most important, what we have observed and learned from it
Composing an App with Free Monads (using Cats)Hermann Hueck
In this talk I will explain what Free Monads are and how to use them (using the Cats implementation).
After having shown the basics I build a small app by composing several
Free Monads to a small program.
I discuss the pros and cons of this technique.
Finally I will demonstrate how to avoid some boilerplate with the FreeK library.
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.
We describe the deployment and use of Globus Compute for remote computation. This content is aimed at researchers who wish to compute on remote resources using a unified programming interface, as well as system administrators who will deploy and operate Globus Compute services on their research computing infrastructure.
How Recreation Management Software Can Streamline Your Operations.pptxwottaspaceseo
Recreation management software streamlines operations by automating key tasks such as scheduling, registration, and payment processing, reducing manual workload and errors. It provides centralized management of facilities, classes, and events, ensuring efficient resource allocation and facility usage. The software offers user-friendly online portals for easy access to bookings and program information, enhancing customer experience. Real-time reporting and data analytics deliver insights into attendance and preferences, aiding in strategic decision-making. Additionally, effective communication tools keep participants and staff informed with timely updates. Overall, recreation management software enhances efficiency, improves service delivery, and boosts customer satisfaction.
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Shahin Sheidaei
Games are powerful teaching tools, fostering hands-on engagement and fun. But they require careful consideration to succeed. Join me to explore factors in running and selecting games, ensuring they serve as effective teaching tools. Learn to maintain focus on learning objectives while playing, and how to measure the ROI of gaming in education. Discover strategies for pitching gaming to leadership. This session offers insights, tips, and examples for coaches, team leads, and enterprise leaders seeking to teach from simple to complex concepts.
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.
A Comprehensive Look at Generative AI in Retail App Testing.pdfkalichargn70th171
Traditional software testing methods are being challenged in retail, where customer expectations and technological advancements continually shape the landscape. Enter generative AI—a transformative subset of artificial intelligence technologies poised to revolutionize software testing.
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.
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.
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.
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.
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus
As part of the DOE Integrated Research Infrastructure (IRI) program, NERSC at Lawrence Berkeley National Lab and ALCF at Argonne National Lab are working closely with General Atomics on accelerating the computing requirements of the DIII-D experiment. As part of the work the team is investigating ways to speedup the time to solution for many different parts of the DIII-D workflow including how they run jobs on HPC systems. One of these routes is looking at Globus Compute as a way to replace the current method for managing tasks and we describe a brief proof of concept showing how Globus Compute could help to schedule jobs and be a tool to connect compute at different facilities.
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTier1 app
Even though at surface level ‘java.lang.OutOfMemoryError’ appears as one single error; underlyingly there are 9 types of OutOfMemoryError. Each type of OutOfMemoryError has different causes, diagnosis approaches and solutions. This session equips you with the knowledge, tools, and techniques needed to troubleshoot and conquer OutOfMemoryError in all its forms, ensuring smoother, more efficient Java applications.
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.
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.
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
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?
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.
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Functional programming-advantages
1. What did functional programming ever do for us
(software engineers)?
An extreme pragmatic and un-academic approach
Sergei Winitzki
Academy by the Bay
2020-08-22
Sergei Winitzki (ABTB) Why functional programming 2020-08-22 1 / 18
2. Overview: Advantages of functional programming
Features of functional programming are being added to many languages
What are these features?
What advantages do they give programmers?
Programmer-facing features listed in the increasing order of complexity
(and decreasing order of advantage-to-cost ratio)
1 Write iterative code without loops
2 Use functions parameterized by types, checked by compiler
3 Use disjunctive types to model special cases, errors, etc.
4 Use special syntax for chaining effectful computations
Sergei Winitzki (ABTB) Why functional programming 2020-08-22 2 / 18
3. Feature 1: Loop-free iterative programs. Transformation
An easy interview question:
Given an array of integers, find all pairs that sum to a given number
Solutions using loops: 10-20 lines of code
FP solution with O(n2) complexity:
# Python
[ (x, y) for x in array for y in array if x + y == n ]
// Scala
for { x <- array; y <- array; if x + y == n } yield (x, y)
-- Haskell
do; x <- array; y <- array; guard (x + y == n); return (x, y)
FP solution with O(n log n) complexity:
// Scala
val hash = array.toSet
for { x <- hash; if hash contains (n - x) } yield (x, n - x)
Sergei Winitzki (ABTB) Why functional programming 2020-08-22 3 / 18
4. Feature 1: Loop-free iterative programs. Aggregation
Given an array of integers, compute the sum of square roots of all
elements except negative ones
# Python
sum( [ sqrt(x) for x in givenArray if x >= 0 ] )
// Scala
givenArray.filter(_ >= 0).map(math.sqrt).sum
Given a set of integers, compute the sum of those integers which are
non-negative and whose square root is also present in the set
Solution using loops: 15-20 lines of code
FP solution:
givenSet // Scala
.filter { x => x >= 0 && givenSet.contains(math.sqrt(x)) }
.sum
Compute a positive integer from a given array of its decimal digits
digits.reverse.zipWithIndex // Scala
.map { case (d, i) => d * math.pow(10, i).toInt } .sum
Sergei Winitzki (ABTB) Why functional programming 2020-08-22 4 / 18
5. Feature 1: Loop-free iterative programs. Induction
Compute the mean value of a given sequence in single pass
scala> Seq(4, 5, 6, 7).foldLeft((0.0, 0.0)) {
| case ((sum, count), x) => (sum + x, count + 1)
| }.pipe { case (sum, count) => sum / count }
res1: Double = 5.5
Any inductive definition can be converted to a “fold”
Base case is the initial value
Inductive step is the updater function
Sergei Winitzki (ABTB) Why functional programming 2020-08-22 5 / 18
6. Feature 1: Loop-free iterative programs. Other applications
The implementation of map, filter, fold, flatMap, groupBy, sum, etc.,
may be asynchronous (Akka Streams), parallel, and/or distributed
(Spark, Flink)
The programmer writes loop-free code in the map/filter/reduce style
The runtime engine implements parallelism, fault tolerance, etc.
Many types of programmer errors are avoided automatically
What we need to support programming in the map/filter/reduce style:
Collections with user-definable methods
Functions (“lambdas”) passed as parameters to other functions
Easy work with tuple types
Lambdas were added to most programming languages by 2015
Sergei Winitzki (ABTB) Why functional programming 2020-08-22 6 / 18
7. Feature 2: Type parameters. Usage
Collections can have types parameterized by element type
Array of integers: Array[Int]
Array of strings: Array[String]
Array of arrays of pairs of integers and strings: Array[Array[(Int,
String)]]
Methods such as map, zip, flatMap, groupBy change the type parameters
Seq(4, 5, 6, 7) // Seq[Int]
.zip(Seq("a", "b", "c", "d")) // Seq[(Int, String)]
.map { case (i, s) => s"$s : $i" } // Seq[String]
The compiler prevents using incorrect type parameters anywhere
Sergei Winitzki (ABTB) Why functional programming 2020-08-22 7 / 18
8. Feature 2: Type parameters. Language features
Code can be written once, then used with different type parameters
Example (Scala):
def map[A, B](xs: Seq[A])(f: A => B): Seq[B] = ...
Collections (Array, Set, etc.) with type parameters support such
methods
Many programming languages have type parameters
Functions with type parameters were added to Java in 2006
C++ can imitate this functionality with templates
Go-lang might get type parameters in the future
Sergei Winitzki (ABTB) Why functional programming 2020-08-22 8 / 18
9. Feature 3: Disjunctive types
Enumeration type (enum) describes a set of disjoint possibilities:
enum Color { RED, GREEN, BLUE; } // Java
A value of type Color can be only one of the three possibilities
Disjunctive types are “enriched” enum types, carrying extra values:
// Scala 3
enum RootOfEq { case NoRoots(); case OneRoot(x: Float); }
The switch is “enriched” to extract data from disjunctive values
// Scala
roots match {
case OneRoot(x) => // May use ‘x‘ in this expression.
case NoRoots() => // May not use ‘x‘ here by mistake.
}
Disjunctive types describe values from “tagged union” sets
OneRoot(x) ∼= the set of all Float values
NoRoots() ∼= the set consisting of a single value
RootOfEq ∼= either some Float value or the special value NoRoots()
Sergei Winitzki (ABTB) Why functional programming 2020-08-22 9 / 18
10. Feature 3: Disjunctive types. Adoption in languages
Disjunctive types and pattern matching are required for FP
Introduced in Standard ML (1973)
Supported in all FP languages (OCaml, Haskell, F#, Scala, Swift, ...)
The support of disjunctive types only comes in FP-designed languages
Not supported in C, C++, Java, JavaScript, Python, Go, ...
Not supported in relational languages (Prolog, SQL, Datalog, ...)
Not supported in configuration data formats (XML, JSON, YAML, ...)
Logical completeness of the type system:
Scala type Logic operation Logic notation Type notation
(A, B) conjunction A ∧ B A × B
Either[A, B] disjunction A ∨ B A + B
A => B implication A ⇒ B A → B
Unit true 1
Nothing false ⊥ 0
Programming is easier in languages having a complete logic of types
“Hindley-Milner type system”
Sergei Winitzki (ABTB) Why functional programming 2020-08-22 10 / 18
11. Feature 4: Chaining of effects. Motivation
How to compose computations that may fail with an error?
A “result or error” disjunctive type: Try[A] ∼= Either[Throwable, A]
In Scala, Try[A] is a disjunction of Failure[Throwable] and Success[A]
Working with Try[A] requires two often-used code patterns:
Use Try[A] in a computation that cannot fail, f: A => B
Success(a) goes to Success(f(a)) but Failure(t) remains unchanged
Use Try[A] in a computation that can fail, g: A => Try[B]
Success(a) goes to g(a) while Failure(t) remains unchanged
Sergei Winitzki (ABTB) Why functional programming 2020-08-22 11 / 18
12. Feature 4: Chaining of effects. Implementation
Implementing the two code patterns using pattern matching:
Pattern 1: use Try[A] in a computation that cannot fail
tryGetFileStats() match {
case Success(stats) => Success(stats.getTimestamp)
case Failure(exception) => Failure(exception)
}
Pattern 2: use Try[A] in a computation that can fail
tryOpenFile() match {
case Success(file) => tryRead(file) // Returns Try[Array[Byte]]
case Failure(exception) => Failure(exception)
}
Sergei Winitzki (ABTB) Why functional programming 2020-08-22 12 / 18
13. Feature 4: Chaining of effects. Implementation
The two patterns may be combined at will
// Read a file, decode UTF-8, return the number of chars.
def utfChars(name: String): Try[Int] = tryOpenFile(name) match {
case Success(file) => tryRead(file) match {
case Success(bytes) => tryDecodeUTF8(bytes) match {
case Success(decoded) => Success(decoded.length)
case Failure(exception) => Failure(exception)
}
case Failure(exception) => Failure(exception)
}
case Failure(exception) => Failure(exception)
}
The code is awkwardly nested and repetitive
This sort of code is common in go-lang programs:
err1, res1 := tryOpenFile();
if (res1 != nil) {
err2, res2 := tryRead(res1);
if (res2 != nil) { ... } // Continue with no errors.
else ... // Handle second error.
else ... // Handle first error.
Sergei Winitzki (ABTB) Why functional programming 2020-08-22 13 / 18
14. Feature 4: Chaining of effects. Using map and flatMap
Implement the two code patterns using map and flatMap:
Try(a).map(f) – use with f: A => B that cannot fail
Try(a).flatMap(g) – use with g: A => Try[B] that can fail
def fmap[A, B](f: A => B): Try[A] => Try[B]
def flm[A, B](g: A => Try[B]): Try[A] => Try[B]
Pattern 1: use Try[A] in a computation that cannot fail
tryGetFileStats() match {
case Success(stats) => Success(stats.getTimestamp)
case Failure(exception) => Failure(exception)
}
Pattern 2: use Try[A] in a computation that can fail
tryOpenFile() match {
case Success(file) => read(file) // Returns Try[InputStream]
case Failure(exception) => Failure(exception)
}
Sergei Winitzki (ABTB) Why functional programming 2020-08-22 14 / 18
15. Feature 4: Chaining of effects. Special syntax
Using map and flatMap, the code from the previous slide simplifies:
tryGetFileStats().map(stats => stats.getTimestamp)
tryOpenFile().flatMap(file => read(file))
We can now write code like this (avoiding nesting and repetition):
Try(one()).map { x => f(x) }.flatMap { y => Try(another(y)) }
Instead of a chain of map and flatMap methods, use a special syntax:
for {
x <- Try(one())
y = f(x)
z <- Try(another(y))
} yield z
Resembles the syntax for nested loops (“for-comprehension”)
for { x <- list1; y <- list2 } yield p(x, y) // Scala
[ p(x, y) for y in list2 for x in list1 ] // Python
In Haskell: “do notation”, in F#: “computation expressions”
Sergei Winitzki (ABTB) Why functional programming 2020-08-22 15 / 18
16. Feature 4: Chaining of effects. Special syntax
Using the special syntax, a chain of computations looks like this:
// Read a file, decode UTF-8, return the number of chars.
def utfChars(name: String): Try[Int] = for {
file <- tryOpenFile(name)
bytes <- tryRead(file)
decoded <- tryDecodeUTF8(bytes)
length = decoded.length
} yield length
Sergei Winitzki (ABTB) Why functional programming 2020-08-22 16 / 18
17. Features 1-4 may be combined at will
The main advantages in practical coding come from combining features 1-4
of functional programming
Use functional methods on collections with type parameters
Use disjunctive types to represent program requirements
Avoid explicit loops and make sure all types match
Compose programs at high level by chaining effects (Try, Future, ...)
Sergei Winitzki (ABTB) Why functional programming 2020-08-22 17 / 18
18. Summary
FP proposes 4 essential features that make programming easier
loop-free iteration, type parameters, disjunctive types, chaining syntax
other, more advanced features have lower cost/advantage ratios
All “FP languages” have these features and give the same advantages
OCaml, Haskell, Scala, F#, Swift, Rust, Elm, ...
Most “non-FP languages” lack at least 2 of these features
Lack of features may be compensated but raises the cost of their use
Sergei Winitzki (ABTB) Why functional programming 2020-08-22 18 / 18