0% found this document useful (0 votes)
47 views

Structured Programming - Lecture 3

This document discusses structured programming and functional programming concepts. It covers recursion, arrow functions, functions as first-class objects, and provides several examples of solving a problem of executing a function only once in both object-oriented and functional programming paradigms.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views

Structured Programming - Lecture 3

This document discusses structured programming and functional programming concepts. It covers recursion, arrow functions, functions as first-class objects, and provides several examples of solving a problem of executing a function only once in both object-oriented and functional programming paradigms.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 33

SWE4205 – STRUCTURED

PROGRAMMING
A. A. Datti
COURSE OUTLINE
1. Introduction to Structured Programming
2. What is functional programming?
3. Functional vs. Object-oriented programming
4. Functions, Closures and scopes
5. Understanding your application’s control flow
6. Method chaining and Function chaining
7. Reasoning about your code
8. Learning to think recursively
SWE4205 - STRUCTURED PROGRAMMING 2
WHAT IS FUNCTIONAL
PROGRAMMING? – Lecture 3
PART 2
RECURSION
Recursion is the most potent tool for developing algorithms and a
great aid for solving large classes of problems.

The idea is that a function can at a certain point call itself, and
when that call is done, continue working with whatever result it
has received.
RECURSION
The most often quoted example is the factorial function (the factorial of n is written
as n!) as defined for nonnegative integer values:
RECURSION

Recursion will be a great aid for the design of algorithms. By using recursion, you could do
without any while or for loops
ARROW FUNCTIONS
Arrow functions are just a shorter, more succinct way of creating an (unnamed)
function.
Arrow functions can be used almost everywhere a classical function can be used, except
that they cannot be used as constructors.
The syntax is either
(parameter1, parameter2, ...) => { statements }
or
(parameter1, parameter2, ...) => expression.
The first allows you to write as much code as you want, and the second is short for
{ return expression }.
ARROW FUNCTIONS
A new version of the factorial code could be like the following code:
ARROW FUNCTIONS
Arrow functions are usually called anonymous functions because of their lack of a
name.
If you need to refer to an arrow function, you'll have to assign it to a variable or
object attribute, as we did here; otherwise, you won't be able to use it.

When the arrow function has a single parameter, you can omit the parentheses
around it
FUNCTIONS AS FIRST-CLASS
OBJECTS
Saying that functions are first-class objects (also called first-class citizens)
means that you can do everything with functions that you can do with other
objects.

For example, you can store a function in a variable, you can pass it to a
function, you can print it out, and so on.

This is really the key to doing FP; we will often be passing functions as
parameters (to other functions) or returning a function as the result of a
function call
A PROBLEM – DOING
SOMETHING ONLY ONCE
Consider an e-commerce site where the user can fill their shopping cart, and
in the end, they must click on a Bill me button so their credit card will be
charged.

However, the user shouldn't click twice (or more) or they will be billed
several times.

The HTML part of your application might have something like this
somewhere:
…CONTINUED
And, among the scripts, you'd have something similar to the
following code:

How can we manage to avoid the user clicking more than once?
SOLUTION 1 – HOPING FOR
THE BEST!
Do nothing, tell the user not to click twice, and hope for the best!

Your solution might simply look like the following code:

Okay, so this isn't actually a solution; let's move on to more serious proposals.
SOLUTION 2 – USING A
GLOBAL FLAG
You'd define a flag named something like clicked, initialized with false.
When the user clicks on the button, if clicked was false, you'd change it to true and
execute the function; otherwise, you wouldn't do anything at all.

 You are using a global


variable, and you could
change its value by accident.

 You must also remember to


re-initialize it to false when
the user starts buying again.
SOLUTION 3 – REMOVING THE
HANDLER
Instead of having the function avoid repeated clicks, we might just remove the
possibility of clicking altogether.
The following code does just that; the first thing that billTheUser() does is remove
the onclick handler from the button, so no further calls will be possible:
SOLUTION 3 - …CONTINUED
This solution also has some problems:

 The code is tightly coupled to the button, so you won't be able to reuse it
elsewhere.

 You must remember to reset the handler, otherwise, the user won't be able to
make a second buy.
SOLUTION 4 – CHANGING THE
HANDLER
A variant to the previous solution would be not to remove the click function, but
rather assign a new one instead.
We are using functions as first-class objects here when we assign the alreadyBilled()
function to the click event.
The function warning the user that they have already clicked could be something as
follows:
SOLUTION 4 - …CONTINUED
Our billTheUser() function would then be like the following code—and note how
instead of assigning null to the onclick handler as in the previous section, now the
alreadyBilled() function is assigned:

If the user clicks a second time, they'll get a warning not to do that, but they won't be
billed again.
However, this solution still has the very same objections as the previous one (code
coupled to the button & needing to reset the handler).
SOLUTION 5 – DISABLING THE
BUTTON
A similar idea here is instead of removing the event handler, we can disable the button so the user
won't be able to click.
You might have a function like the following code, which does exactly that by setting the disabled
attribute of the button:

This also works, but we still have objections as with the previous solutions (coupling the code to
the button & needing to re-enable the button
SOLUTION 6 – REDEFINING
THE HANDLER
Another idea: instead of changing anything in the button, let's have the event handler
change itself.
The trick is in the second line; by assigning a new value to the billTheUser variable,
we are actually dynamically changing what the function does!
The first time you call the function, it will do its thing, but it will also change itself
out of existence, by giving its name to a new function:
SOLUTION 6 - …CONTINUED
There's a special trick in the solution. Functions are global, so the billTheUser=...
line actually changes the function's inner workings.
From that point on, billTheUser will be the new (null) function.
This solution is still hard to test.
Even worse, how would you restore the functionality of billTheUser, setting it back
to its original objective?
A FUNCTIONAL SOLUTION TO
OUR PROBLEM
The original function (the one that may be called only once) should do whatever it is
expected to do and nothing else. No Side effects

We don't want to modify the original function in any way.

We need to have a new function that will call the original one only once.

We want a general solution that we can apply to any number of original functions
A HIGHER-ORDER SOLUTION
(1)
If we don't want to modify the original function, we'll create a higher-order function,
which we'll name once().
This function will receive a function as a parameter and will return a new function,
which will work only a single time.
A HIGHER-ORDER SOLUTION
(2)
The first line shows that once() receives a function (fn) as its parameter

We are defining an internal, private done variable.

Each time you apply once() to some function, a new, distinct done variable
will be created and will be accessible only from the returned function.

The return (...args) => ... line says that once() will return a function, with
some (one or more, or possibly zero) parameters.
A HIGHER-ORDER SOLUTION
(3)
We assign done = true before calling fn(), just in case that function throws
an exception.

Of course, if you don't want to disable the function unless it has successfully
ended, then you could move the assignment just below the fn() call.

After the setting is done, we finally call the original function. Note the use of
the spread operator to pass along whatever parameters the original fn() had.
A HIGHER-ORDER SOLUTION
(4)
So, how would we use it? We don't even need to store the newly generated function
in any place. We can simply write the onclick method, shown as follows:

When the user clicks on the button, the function that gets called with the (some,
sales, data) argument isn't billTheUser(), but rather the result of having called
once() with billTheUser as a parameter. That result is the one that can be called only
a single time.
TESTING THE SOLUTION
MANUALLY
We can run a simple test. Let's write a squeak() function that will, appropriately,
squeak when called! The code is simple:
TESTING THE SOLUTION
MANUALLY
If we apply once() to it, we get a new function that will squeak only once. See the
highlighted line in the following code:
FUNCTIONAL VS
OBJECT ORIENTED
OBJECT ORIENTED SEAGULL
APPLICATION
Here is a seagull application. When flocks conjoin they become a larger flock, and
when they breed, they increase by the number of seagulls with whom they're breeding
FUNCTIONAL SEAGULL
APPLICATION
Let's try again, this time using a more functional approach:
FUNCTIONAL VS OBJECT
ORIENTED

Are both answers the same?

Why?
END

You might also like