This document provides an overview of a lecture on functional programming in Scala. It covers the following topics:
1. A recap of functional programming principles like functions as first-class values and no side effects.
2. An introduction to the Haskell programming language including its syntax for defining functions.
3. How functions are defined in Scala and how they are objects at runtime.
4. Examples of defining the factorial function recursively in Haskell and Scala, and making it tail recursive.
5. Concepts of first-class functions, currying, partial application, and an example of implementing looping in Scala using these techniques.
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.
Introduction to Functional Programming in JavaScripttmont
A presentation I did for work on functional programming. It's meant as an introduction to functional programming, and I implemented the fundamentals of functional programming (Church Numerals, Y-Combinator, etc.) in JavaScript.
While doing programming in any programming language, you need to use various variables to store various information. Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.
You may like to store information of various data types like character, wide character, integer, floating point, double floating point, boolean etc. Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory.
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.
Introduction to Functional Programming in JavaScripttmont
A presentation I did for work on functional programming. It's meant as an introduction to functional programming, and I implemented the fundamentals of functional programming (Church Numerals, Y-Combinator, etc.) in JavaScript.
While doing programming in any programming language, you need to use various variables to store various information. Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.
You may like to store information of various data types like character, wide character, integer, floating point, double floating point, boolean etc. Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory.
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2Philip Schwarz
(download for perfect quality) See aggregation functions defined inductively and implemented using recursion.
Learn how in many cases, tail-recursion and the accumulator trick can be used to avoid stack-overflow errors.
Watch as general aggregation is implemented and see duality theorems capturing the relationship between left folds and right folds.
Through the work of Sergei Winitzki and Richard Bird.
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...Philip Schwarz
(download for perfect quality) See aggregation functions defined inductively and implemented using recursion.
Learn how in many cases, tail-recursion and the accumulator trick can be used to avoid stack-overflow errors.
Watch as general aggregation is implemented and see duality theorems capturing the relationship between left folds and right folds.
Through the work of Sergei Winitzki and Richard Bird.
This version corrects the following issues:
slide 32: = reverse --> reverse =
Slide 33: 100_000 -> 1_000_000
It also adds slides 36, 37 and 38
Principles of functional progrmming in scalaehsoon
a short outline on necessity of functional programming and principles of functional programming in Scala.
In the article some keyword are used but not explained (to keep the article short and simple), the interested reader can look them up in internet.
Functional Programming Past Present FutureIndicThreads
Presented at the IndicThreads.com Software Development Conference 2016 held in Pune, India. More at http://www.IndicThreads.com and http://Pune16.IndicThreads.com
--
following is work on Advance Python part 1 Functional Programming in Python
for code and more details plz do visit
https://lnkd.in/dnQF95z
for more free study material and Projects follow on
Github
https://lnkd.in/gYKtuB3
LinkedIn
https://lnkd.in/daSvf_P
#python #datascience #programming #machinelearning #github #deeplearning #coding #developer #projects #work #developers #linkedin #google #amazonindia#IBM
Similar to Programming in Scala - Lecture Two (20)
This was the opening presentation of the Zenoh Summit in June 2022. The presentation goes through the motivations that lead to the design of the zenoh protocol and provides an introduction of its core concepts. This is the place to start to understand why you should care about zenoh and the way in which is disrupts existing technologies.
The recording for this presentation is available at https://bit.ly/3QOuC6i
Zenoh is rapidly growing Eclipse project that unifies data in motion, data at rest and computations. It elegantly blends traditional pub/sub with geo distributed storage, queries and computations, while retaining a level of time and space efficiency that is well beyond any of the mainstream stacks. This presentation will provide an introduction to Eclipse Zenoh along with a crisp explanation of the challenges that motivated the creation of this project. We will go through a series of real-world use cases that demonstrate the advantages brought by Zenoh in enabling and optimising typical edge scenarios and in simplifying the development of any scale distributed applications.
Data Decentralisation: Efficiency, Privacy and Fair MonetisationAngelo Corsaro
A presentation give at the European H-Cloud Conference to motivate decentralisation as a mean to improve energy efficiency, privacy, and opportunity for monetisation for your digital footprint.
zenoh: zero overhead pub/sub store/query computeAngelo Corsaro
Unifies data in motion, data in-use, data at rest and computations.
It carefully blends traditional pub/sub with distributed queries, while retaining a level of time and space efficiency that is well beyond any of the mainstream stacks.
It provides built-in support for geo-distributed storages and distributed computations
zenoh -- the ZEro Network OverHead protocolAngelo Corsaro
This presentation introduces the key ideas behind zenoh -- an Internet scale data-centric protocol that unifies data-sharing between any kind of device including those constrained with respect to the node resources, such as computational resources and power, as well as the network.
zenoh -- the ZEro Network OverHead protocolAngelo Corsaro
This presentation introduces the key ideas behind zenoh -- an Internet scale data-centric protocol that unifies data-sharing between any kind of device including those constrained with respect to the node resources, such as computational resources and power, as well as the network.
Fog computing aims at providing horizontal, system-level, abstractions to distribute computing, storage, control and networking functions closer to the user along a cloud-to-thing continuum. Whilst fog computing is increasingly recognised as the key paradigm at the foundation of Consumer and Industrial Internet of Things (IoT), most of the initiatives on fog computing focus on extending cloud infrastructure. As a consequence, these infrastructure fall short in addressing heterogeneity and resource constraints characteristics of fog computing environments.
fog⌀5 (read as fog O-five or fog OS) is an Eclipse IoT Project that is building a fog computing infrastructure from first principle. In other terms, fog⌀5 has been designed to address the challenges induced by fog computing in terms of heterogeneity, decentralisation, resource constraints, geographical scale and security.
This webcast will introduce fog⌀5, motivate its architecture and building blocks as well as provide a demonstration of fog⌀5 provisioning applications that span from the cloud to the things.
The video recording for this presentation is available at https://www.youtube.com/watch?v=Osl3O5DxHF8
Making the right data available at the right time, at the right place, securely, efficiently, whilst promoting interoperability, is a key need for virtually any IoT application. After all, IoT is about leveraging access data – that used to be unavailable – in order to improve the ability to react, manage, predict and preserve a cyber-physical system.
The Data Distribution Service (DDS) is a standard for interoperable, secure, and efficient data sharing, used at the foundation of some of the most challenging Consumer and Industrial IoT applications, such as Smart Cities, Autonomous Vehicles, Smart Grids, Smart Farming, Home Automation and Connected Medical Devices.
In this presentation we will (1) introduce the Eclipse Cyclone DDS project, (2) provide a quick intro that will get you started with Cyclone DDS, (3) present a few Cyclone DDS use cases, and (4) share the Cyclone DDS development road-map.
Fog Computing is a paradigm that complements and extends cloud computing by providing an end-to-end virtualisation of computing, storage and communication resources. As such, fog computing allow applications to be transparently provisioned and managed end-to-end. This presentation first motivates the need for fog computing, then introduced fog05 the first and only Open Source fog computing platform!
Data Sharing in Extremely Resource Constrained EnvionrmentsAngelo Corsaro
This presentation introduces XRCE a new protocol for very efficiently distributing data in resource constrained (power, network, computation, and storage) environments. XRCE greatly improves the wire efficiency of existing protocol and in many cases provides higher level abstractions.
RUSTing is not a tutorial on the Rust programming language.
I decided to create the RUSTing series as a way to document and share programming idioms and techniques.
From time to time I’ll draw parallels with Haskell and Scala, having some familiarity with one of them is useful but not indispensable.
Vortex II -- The Industrial IoT Connectivity StandardAngelo Corsaro
The large majority of commercial IoT platforms target consumer applications and fall short in addressing the requirements characteristic of Industrial IoT. Vortex has always focused on addressing the challenges characteristic of Industrial IoT systems and with 2.4 release sets a the a new standard!
This presentation will (1) introduce the new features introduced in with Vortex 2.4, (2) explain how Vortex 2.4 addresses the requirements of Industrial Internet of Things application better than any other existing platform, and (3)showcase how innovative companies are using Vortex for building leading edge Industrial Internet of Things applications.
Fog computing has emerged as a new paradigm for architecting IoT applications that require greater scalability, performance and security. This talk will motivate the need to Fog Computing and explain what it is and how it differs from other initiatives in Telco such as Mobile/Multiple-Access Edge Computing.
Introduced in 2004, the Data Distribution Service (DDS) has been steadily growing in popularity and adoption. Today, DDS is at the heart of a large number of mission and business critical systems, such as, Air Traffic Control and Management, Train Control Systems, Energy Production Systems, Medical Devices, Autonomous Vehicles, Smart Cities and NASA’s Kennedy Space Centre Launch System.
Considered the technological trends toward data-centricity and the rate of adoption, tomorrow, DDS will be at the at the heart of an incredible number of Industrial IoT systems.
To help you become an expert in DDS and exploit your skills in the growing DDS market, we have designed the DDS in Action webcast series. This series is a learning journey through which you will (1) discover the essence of DDS, (2) understand how to effectively exploit DDS to architect and program distributed applications that perform and scale, (3) learn the key DDS programming idioms and architectural patterns, (4) understand how to characterise DDS performances and configure for optimal latency/throughput, (5) grow your system to Internet scale, and (6) secure you DDS system.
Introduced in 2004, the Data Distribution Service (DDS) has been steadily growing in popularity and adoption. Today, DDS is at the heart of a large number of mission and business critical systems, such as, Air Traffic Control and Management, Train Control Systems, Energy Production Systems, Medical Devices, Autonomous Vehicles, Smart Cities and NASA’s Kennedy Space Centre Launch System.
Considered the technological trends toward data-centricity and the rate of adoption, tomorrow, DDS will be at the at the heart of an incredible number of Industrial IoT systems.
To help you become an expert in DDS and exploit your skills in the growing DDS market, we have designed the DDS in Action webcast series. This series is a learning journey through which you will (1) discover the essence of DDS, (2) understand how to effectively exploit DDS to architect and program distributed applications that perform and scale, (3) learn the key DDS programming idioms and architectural patterns, (4) understand how to characterise DDS performances and configure for optimal latency/throughput, (5) grow your system to Internet scale, and (6) secure you DDS system.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
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.
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.
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Are you looking to streamline your workflows and boost your projects’ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, you’re in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part “Essentials of Automation” series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Here’s what you’ll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
We’ll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Don’t miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
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.
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
Neuro-symbolic (NeSy) AI is on the rise. However, simply machine learning on just any symbolic structure is not sufficient to really harvest the gains of NeSy. These will only be gained when the symbolic structures have an actual semantics. I give an operational definition of semantics as “predictable inference”.
All of this illustrated with link prediction over knowledge graphs, but the argument is general.
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
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.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
5. Functional Programming
Functional Programming is a method of program construction that:
• Emphasises functions and their applications as opposed to commands and
their execution.
• Uses simple mathematical notation that allows problems to be described
clearly and concisely.
• Has a simple mathematical bases that supports equational reasoning about
the properties of a program.
A functional programming languages is guided by two main ideas, functions as
first-class values and no side-effects.
3
6. Functions as First-Class Values
In a functional programming language:
• A function is a value as an Integer or a String.
• Functions can be passed as arguments, returned as values as well as stored
into variables.
• Functions can be named or anonymous and can be defined inside other
functions.
4
7. No Side-Effects
• In a functional programming language, the result of applying some
arguments to a functions should only depend on the input. In other terms,
applying the same input to a given function always gives the same output.
• Functions that satisfy this property are know to be referentially transparent.
• Functional programming languages ecnourage the use of immutable data
structures and referentually transparent functions.
Note: it is worth comparing the functional approach with the imperative style
programming were everything is based on mutable data and side-effects.
5
9. The Haskell Programming Language
Haskell is a pure, lazy, functional programming language first defined in 1990.
The programming language was named after Haskell B. Curry, who was one of
the pioneers of λ-calculus, a mathematical theory of functions that has been an
inspiration to designers of a number of functional programming languages.
The latest version of the language is Haskell-2010 and a working group was
established in 2016 to define Haskell-2020.
The Haskell’s home is http://www.haskell.org
6
11. Functions in Haskell
Haskell’s notation to denotate a function f that takes an argument of type X
and returns a result of type Y is:
1 f :: X -> Y
Example
For example:
1 sin :: Float -> Float
2 add :: Integer -> Integer -> Integer
3 reverse :: String -> String
4 sum :: [Integer] -> Integer
Notice how Haskell’s functions declaration is extremely close to that used in
mathematics. This is not accidental, and we will see the analogy goes quite far.
7
12. Getting Started with Haskell
The best way to get started with Haskell is to unstall stack from
https://docs.haskellstack.org/en/stable/README/.
Once installed you can start Haskell’s REPL and experiment a bit:
1 > stack repl
2 Prelude> let xs = [1..10]
3 Prelude> :t xs
4 xs :: (Num t, Enum t) => [t]
5 Prelude> :t sum
6 sum :: (Num a, Foldable t) => t a -> a
7 Prelude> sum xs
8 55
9 Prelude> :t foldl
10 foldl :: Foldable t => (b -> a -> b) -> b -> t a -> b
11 Prelude> foldl (+) 0 xs
12 55
13 Prelude> foldl (*) 1 xs
14 3628800
8
14. Functions in Scala
Scala’s notation to denotate a function f that takes an argument of type X and
returns a result of type Y is:
1 def f(x: X): Y
Example
For example:
1 def sin(x: Float): Float
2 def add(a: Integer, b: Integer): Integer
3 def reverse(s: String): String
4 def sum(xs: Array[Integer]): Integer
Notice how Haskell’s functions declaration is extremely close to that used in
mathematics. This is not accidental, and we will see the analogy goes quite far.
9
15. Functions are Objects
In Scala function a function:
def f (t1 : T1, t2 : T2, ..., tn : Tn) : R
is are represented at runtime as objects whose type is:
trait Fun[−T1, −T2, ..., −Tn, +R] extends AnyRef
10
16. Local Functions
Some times, it is useful to define named functions that don’t pollute the global
namespace but instead are available only within a given function scope.
Scala makes this possible by defining local functions, in other terms, functions
that are defined inside another function.
1 def outer(x: X): Y = {
2 def inner(a: A): B = {
3 // function body
4 }
5 // ...
6 val b = inner(a)
7 // ...
8 }
11
18. Factorial Exercise
Last lecture I had asked you to look into finding a tail recursive definition of the
factorial. Let’s see how to get there and how inner function can help out.
Anybody wants to show his/her solution?
12
20. Factorial Definition in Scala – Take 1
If you’d tried to write the factorial, you probably ended up writing something like
this:
1 def factorial(n: Int): Int = if (n == 0) 1 else n * factorial(n-1)
Please notice that for clarity sake I am not asserting n >= 0. This should be
checked for production code.
14
21. Factorial Definition in Scala – Take 2
If you’d tried to write the factorial, you probably ended up writing something like
this:
1 def factorial(n: Int): Int = n match {
2 case 0 => 1
3 case _ if n > 0 => n*factorial(n-1)
4 }
This version looks a bit more like the mathematical definition, which is nice.
15
23. Factorial Definition in Haskell – Take 1
If you’d tried to write the factorial, you probably ended up writing something like
this:
1 factorial :: Integer -> Integer
2 factorial 0 = 1
3 factorial n = n * (factorial n-1)
This version looks a bit more like the mathematical definition, which is nice.
16
24. Factorial Definition in Haskell – Take 2
If you’d tried to write the factorial, you probably ended up writing something like
this:
1 factorial :: Integer -> Integer
2 factorial n = case n of
3 0 -> 1
4 _ -> n* (factorial (n-1))
This version looks a bit more like the mathematical definition, which is nice.
17
25. Evaluating the Factorial
Below is the equational substitution for factorial 3 as well as its evaluation
stack.
factorial 3 = 3∗(factorial 2) = 3∗2∗(factorial 1) =
3 ∗ 2 ∗ 1 ∗ (factorial 0) = 3 ∗ 2 ∗ 1 ∗ 1 = 6
...
1
1*(factorial 0)
2*(factorial 1)
3*(factorial 2)
factorial 3
...
18
26. Tail Recursion
The implementations of the factorial we have seen thus far take a linear number
of stack frames to evaluate.
This is not desirable. A recursive functions that does not evaluate with a bound
the stack size may fail at run-time because of stack overflows.
For efficiency and run-time robustness, whenever possible, is is best to write
recursive functions so that they are tail recursive.
Definition
Tail-recursive functions are functions in which all recursive calls are tail calls and
hence do not build up any deferred operations.
19
27. Tail Recursive Factorial
1 def factorial(n: Int): Int = {
2 @tailrec
3 def afact(a: Int, n: Int): Int =
4 if (n == 0) a else afact(a * n, n - 1)
5
6 afact(1, n)
7 }
As you can see from the fragment above we are carrying state along calls through
an accumulator. This is a technique used often to transform a function into tail
recursive.
The @tailrec annotation is used to tell the Scala compiler that this call is
supposed to be tail-recursive. If this is not the case, the compiler will raise a
warning.
20
29. First-Class Functions
Scala has first-class functions. Beside being able to define named functions, it is
possible to write functions as unnamed literals and to pass them as values.
Example
1 val iadd = (a: Int, b: Int) => a + b
2 val isub = (a: Int, b: Int) => a - b
3
4 val i = iadd(1,2)
5
6 val ibinOp = (op: (Int, Int) => Int, a: Int, b:Int) => op(a,b)
7
8 ibinOp(iadd, 1, 2)
9 ibinOp(isub, 1, 2)
21
31. Do we need multiple-arguments functions?
Those with an imperative programming background are lend to think that a
function in general can have n-arguments.
Thus they think of a generic function as: def fun(a : A, b : B, c : C, ...) : X
But is this really needed? Is this the right abstraction?
22
32. Currying
Definition
Let f : X → Y denote a function f from X to Y . The notation X → Y then
denotes all functions from X to Y . Here X and Y may be sets, types or other
kind of mathematical objects.
Given a function f : (X × Y ) → Z, where X × Y denotes the Cartesian products
of X and Y , currying constructs, or makes a new function,
curr(f ) : X → (Y → Z).
That is, curry(f ) takes an argument of type X and returns a function of type
Y → Z. uncurrying is the opposite transformation.
23
33. Looking again at Haskell’s function declaration
Let’s look again at the add function defined earlier:
1 add :: Integer -> Integer -> Integer
This function can be re-written as follows, to make more explicit the currying:
1 add :: Integer -> (Integer -> Integer)
In other terms, Haskell functions are single-parameters functions.
Technically, the add function above takes an Integer parameter and returns a
function that Integer and returns and Integer. The function add can be
applied as follows:
1 Prelude> add 1 2
2 3
3 Prelude> (add 1) 2
4 3
24
34. Looking again at Haskell’s function declaration – cont.
Also notice that the function:
1 add :: (Integer, Integer) -> Integer
Is a single parameter functions that takes a tuple of two Integer and returns an
Integer.
The function add can be applied as follows:
1 Prelude> add (1, 2)
2 3
25
35. Haskell’s function declarations – again
In general a Haskell function has the following form:
f :: A → B → C → ... → Z
When seeing this declaration, you should think as if it was parenthesized as
follows:
f :: A → (B → (C → ...(Y → Z)
Also notice that:
f :: (A → B)− > C
Is a function that takes single parameter of type A → B (a function from A in B)
and returns a C
26
36. Currying in Scala
Scala provides support for curryed functions, but these have to be explicitly
declared as such.
In general, given a function of n arguments:
1 def fun(a: A, b: B, c: C, ...) : X
The curryed function is delcared as follows:
1 def fun(a: A)(b: B)(c: C) ... : X
Thus, in Scala, differently from Haskell, you have to decide at declaration time if
a function is curryed or not.
The syntax is a bit cluttered when compared to Haskell, but the semantics is the
same.
27
37. Be Patient...
Now you may starting thinking that functional programmers are eccentric, or
even a bit insane... But be patient and in a few slides you’ll find out the power
and elegance of curryed functions.
28
38. Partial Application
Definition
Given a function:
f :: T1 → T2 → T3 → ...Tn → T
If we apply this function to arguments:
e1 :: T1, e2 :: T2, ..., ek :: Tk, (k < n)
the result type is given by canceling the k types T1 to Tk, which give the type:
g :: Tk + 1 → Tk + 2... → Tn → T
The resulting function g is obtained by partially applying k < n arguments to f .
29
39. Partial Application in Haskell
Partial application in Haskell extremely straightforward, you just have to provide
(k < n) parameters to the function application.
Example
1 iadd :: Integer -> Integer -> Integer
2 iadd a b = a + b
3 iadd 1 2
4 3
5 iinc = iadd 1
6 :t iinc
7 iinc :: Num a => a -> a
8 iinc 10
9 11
30
40. Partial Application in Haskell
Example
1 ibinOp :: (Integer -> Integer -> Integer) -> Integer -> Integer -> Integer
2 ibinOp op a b = op a b
3
4 isum = ibinOp iadd
5 imul = ibinOp (*)
6 inc = ibinOp (+) 1
7 double = imul 2
31
41. Partial Application in Scala
Partial application in Scala quite similar to Haskell, with the difference that you
have to add a placeholder to indicate the fact that other parameters are missing.
Thus given a curryed function: deffun(t1 : T1)(t2 : T2)(t3 : T3)...(tn : Tn) : T
The partial application of the first k < n parameters is done as follows:
fun(t1)(t2)(t3)...(tk)T
This evaluates to a function with the following signature:
defafun(tk + 1 : Tk + 1)(tk + 2 : Tk + 2)...(tn : Tn) : T
32
42. Partial Application in Scala: Example
Example
1 def cadd(a: Int)(b:Int): Int = a + b
2 cadd(1)(2)
3
4 def csub(a: Int)(b:Int): Int = a - b
5 val cinc = cadd(1)_
6 cinc (10)
7
8 val ibinOp = (op: (Int, Int) => Int, a: Int, b:Int) => op(a,b)
9
10 ibinOp(cadd, 1, 2)
11 ibinOp(isub, 1, 2)
12
13
14 def cbinOp(op: (Int, Int) => Int)(a: Int)(b:Int) = op(a,b)
15
16 val inc = cbinOp (iadd) (1) _
17
18 inc(1)
33
43. Reflections on Partial Applications and Currying
Currying is instrumental for Partial Application, but it also has other uses in
Scala to introduce high level abstractions, such as new control flow that seem as
if they were built-in the language.
Partial application is extremely useful in library design and in higher-order
programming. You can use partially-applied higher-order functions to easily
customize behaviour of your code and of libraries.
34
44. looping in Scala
Let’s assume that we wanted to add a loop construct to scala.
Recall that Scala’s for construct should not be used for looping since as we will
see, it translates to map and flatmap and can be quite expensive as an iterative
construct.
Let’s use what we’ve learned thus far to implement a looping construct.
We would wont the looping construct to look like this:
1 loop (3) { println("Looping...") }
This should produce:
1 Looping...
2 Looping...
3 Looping...
35
45. looping in Scala
The loop function should be defined as the following curried function:
1 @tailrec
2 def loop(n: Int)(body: => Unit): Unit = {
3 if (n > 0) {
4 body
5 loop(n-1)(body)
6 }
7 }
36
47. Lambdas
Definition
A lambda function is an anonymous function, in other terms a function
definition that is not bound to an identifier.
Example
1 val timesTwo = (a: Int) => 2*a
37
48. Closure
Definition
A closure is an anonymous function, in other terms a function definition that is
not bound to an identifier, which captures free variables from the environment.
Example
1 val x = 10
2 val plusX = (a: Int) => a + x
Notice that a as a closure resolves free variables from the environment, is a good
state to carry around context.
38
50. Working with Lists
List are one of the canonical functional data structures.
Let’s explore Scala’s List (see https://www.scala-lang.org/api/current/
scala/collection/immutable/List.html) and let’s see how higher order
programming makes list processing extremely elegant.
39
51. Computing on Lists with Pattern Matching
1 val xs = List(1,2,3,4)
2
3 def sum(xs: List[Int]): Int = xs match {
4 case y::ys => y+sum(ys)
5 case List() => 0
6 }
7
8 def mul(xs: List[Int]): Int = xs match {
9 case y::ys => y*mul(ys)
10 case List() => 1
11 }
12
13 def reverse(xs: List[Int]): List[Int] = xs match {
14 case List() => List()
15 case y::ys => reverse(ys) ::: List(y)
16 }
40
52. Folding Lists
The functions we just wrote for lists can all be expressed in terms of fold
operator.
1 def sum(xs: List[Int]): Int = xs.foldRight(0)(_ + _)
2
3 def sum(xs: List[Int]): Int = xs.foldLeft(0)(_ + _)
4
5 def reversel(ys: List[Int])= ys.foldLeft(List[Int]())((xs: List[Int], x: Int) => x :: xs)
6
7 def reverser(ys: List[Int]) = zs.foldRight(List[Int]())((x: Int, xs: List[Int]) => xs ::: List(x) )
41