Home >Web Front-end >JS Tutorial >Functional Programming in TypeScript

Functional Programming in TypeScript

Patricia Arquette
Patricia ArquetteOriginal
2024-10-19 22:32:29732browse

Functional Programming in TypeScript

Contents

  1. Introduction
  2. TypeScript Environment
  3. Representing Data Through Functions
    1. Sets
    2. Binary Operations
    3. Go Further
  4. Euclidean Plane
    1. Drawing a Disk
    2. Drawing Horizontal and Vertical Half-planes
    3. Functions
    4. Go Further
  5. Fractals
    1. Complex Numbers and Drawing
    2. Mandelbrot Fractal
    3. Go Further

You can find source code here: https://github.com/aelassas/functional-ts

Introduction

In TypeScript, functions are nothing but objects. Hence, functions can be constructed, passed as parameter, returned from functions or assigned into variables. Thus, TypeScript has first-class functions. More precisely, TypeScript supports the following:

  • Higher-order functions arguments
  • Higher-order functions results
  • Nested functions
  • Anonymous functions
  • Closures
  • Partial application (ECMAScript 5)

This article will not discuss the basics of functional programming, as you can find numerous resources on this topic on the Internet. Instead, it will talk about functional programming in TypeScript applied to algebra, numbers, the Euclidean plane, and fractals. The examples provided in this article will start from simple to more complex but always illustrated in a simple, straightforward and easy-to-understand manner.

TypeScript Environment

To run the source code, you'll need to install Node.js. Once Node.js is installed, download the source code archive, unzip it, go to the source code folder you unzipped on a terminal, set up TypeScript environment and install all necessary dependencies with the following command:

npm install

To run numbers' demo, run the following command:

npm run numbers

To run Euclidean plane's demo, run the following command:

npm run plane

To run fractals' demo, run the following command:

npm run fractals

Representing Data Through Functions

Let S be any set of elements a, b, c ... (for instance, the books on the table or the points of the Euclidean plane) and let S' be any subset of these elements (for instance, the green books on the table or the points in the circle of radius 1 centered at the origin of the Euclidean plane).

The Characteristic Function S'(x) of the set S' is a function which associates either true or false with each element x of S.

S'(x) = true if x is in S'
S'(x) = false if x is not in S'

Let S be the set of books on the table and let S' be the set of green books on the table. Let a and b be two green books, and let c and d be two red books on the table. Then:

npm install

Let S be the set of the points in the Euclidean plane and let S' be the set of the points in the circle of radius 1 centered at the origin of the Euclidean plane (0, 0) (unit circle). Let a and b be two points in the unit circle, and let c and d be two points in a circle of radius 2 centered at the origin of the Euclidean plane. Then:

npm run numbers

Thus, any set S' can always be represented by its Characteristic Function. A function that takes as argument an element and returns true if this element is in S', false otherwise. In other words, a set (abstract data type) can be represented through a function in TypeScript.

npm run plane

In the next sections, we will see how to represent some fundamental sets in the algebra of sets through TypeScript in a functional way, then we will define generic binary operations on sets. We will then apply these operations on numbers then on subsets of the Euclidean plane. Sets are abstract data structures, the subsets of numbers and the subsets of the Euclidean plane are the representation of abstract data-structures, and finally the binary operations are the generic logics that works on any representation of the abstract data structures.

Sets

This section introduces the representation of some fundamental sets in the algebra of sets through TypeScript.

Empty set

Functional Programming in TypeScript

Let E be the empty set and Empty its Characteristic function. In algebra of sets, E is the unique set having no elements. Therefore, Empty can be defined as follows:

npm run fractals

Thus, the representation of E in TypeScript can be defined as follows:

S'(x) = true if x is in S'
S'(x) = false if x is not in S'

In algebra of sets, Empty is represented as follows:

Functional Programming in TypeScript

Thus, running the code below:

S'(a) = S'(b) = true
S'(c) = S'(d) = false

gives the following results:

Functional Programming in TypeScript

Set All

Functional Programming in TypeScript

Let S be a set and S' be the subset of S that contains all the elements and All its Characteristic function. In algebra of sets, S' is the full set that contains all the elements. Therefore, All can be defined like this:

S'(a) = S'(b) = true
S'(c) = S'(d) = false

Thus, the representation of S' in TypeScript can be defined as follows:

type Set<T> = (x: T) => boolean

In algebra of sets, All is represented as follows:

Functional Programming in TypeScript

Thus, running the code below:

npm install

gives the following results:

Functional Programming in TypeScript

Singleton Set

Let E be the Singleton set and Singleton its Characteristic function. In algebra of sets, E also known as unit set, or 1-tuple is a set with exactly one element e. Therefore, Singleton can be defined as follows:

npm run numbers

Thus, the representation of E in TypeScript can be defined as follows:

npm run plane

Thus, running the code below:

npm run fractals

gives the following results:

Functional Programming in TypeScript

Other Sets

This section presents subsets of the integers set.

Even Numbers

Let E be the set of even numbers and Even its Characteristic function. In mathematics, an even number is a number which is a multiple of two. Therefore, Even can be defined as follows:

S'(x) = true if x is in S'
S'(x) = false if x is not in S'

Thus, the representation of E in TypeScript can be defined as follows:

S'(a) = S'(b) = true
S'(c) = S'(d) = false

Thus, running the code below:

S'(a) = S'(b) = true
S'(c) = S'(d) = false

gives the following results:

Functional Programming in TypeScript

Odd Numbers

Let E be the set of odd numbers and Odd its Characteristic function. In mathematics, an odd number is a number which is not a multiple of two. Therefore, Odd can be defined as follows:

type Set<T> = (x: T) => boolean

Thus, the representation of E in TypeScript can be defined as follows:

Empty(x) = false if x is in E
Empty(x) = false if x is not in E

Thus, running the code below:

const empty = () => (e: T) => false

gives the following results:

Functional Programming in TypeScript

Multiples of 3

Let E be the set of multiples of 3 and MultipleOfThree its Characteristic function. In mathematics, a multiple of 3 is a number divisible by 3. Therefore, MultipleOfThree can be defined as follows:

console.log('\nEmpty set:')
console.log('Is 7 in {}?', common.empty()(7))

Thus, the representation of E in TypeScript can be defined as follows:

All(x) = true if x is in S

Thus, running the code below:

const all = () => (e: T) => true

gives the following results:

Functional Programming in TypeScript

Multiples of 5

Let E be the set of multiples of 5 and MultipleOfFive its Characteristic function. In mathematics, a multiple of 5 is a number divisible by 5. Therefore, MultipleOfFive can be defined as follows:

npm install

Thus, the representation of E in TypeScript can be defined as follows:

npm run numbers

Thus, running the code below:

npm run plane

gives the following results:

Functional Programming in TypeScript

Prime Numbers

A long time ago, when I was playing with Project Euler problems, I had to resolve the following one:

npm run fractals

To resolve this problem, I first had to write a fast algorithm that checks whether a given number is prime or not. Once the algorithm written, I wrote an iterative algorithm that iterates through primes until the 10 001st prime number was found.

Let E be the set of primes and Prime its Characteristic function. In mathematics, a prime is a natural number greater than 1 that has no positive divisors other than 1 and itself. Therefore, Prime can be defined as follows:

S'(x) = true if x is in S'
S'(x) = false if x is not in S'

Thus, the representation of E in TypeScript can be defined as follows:

S'(a) = S'(b) = true
S'(c) = S'(d) = false

Thus, running the code below to resolve our problem:

S'(a) = S'(b) = true
S'(c) = S'(d) = false

where getPrime is defined below:

type Set<T> = (x: T) => boolean

gives the following results:

Functional Programming in TypeScript

Binary Operations

This section presents several fundamental operations for constructing new sets from given sets and for manipulating sets. Below the Ven diagram in the algebra of sets.

Functional Programming in TypeScript

Union

Functional Programming in TypeScript

Let E and F be two sets. The union of E and F, denoted by E U F is the set of all elements which are members of either E and F.

Let Union be the union operation. Thus, the Union operation can be implemented as follows in TypeScript:

Empty(x) = false if x is in E
Empty(x) = false if x is not in E

Running the code below:

const empty = () => (e: T) => false

gives the following results:

Functional Programming in TypeScript

Intersection

Functional Programming in TypeScript

Let E and F be two sets. The intersection of E and F, denoted by E n F is the set of all elements which are members of both E and F.

Let Intersection be the intersection operation. Thus, the Intersection operation can be implemented as follows in TypeScript:

console.log('\nEmpty set:')
console.log('Is 7 in {}?', common.empty()(7))

Running the code below:

All(x) = true if x is in S

gives the following results:

Functional Programming in TypeScript

Cartesian Product

Functional Programming in TypeScript

Let E and F be two sets. The cartesian product of E and F, denoted by E × F is the set of all ordered pairs (e, f) such that e is a member of E and f is a member of F.

Let CartesianProduct be the cartesian product operation. Thus, the CartesianProduct operation can be implemented as follows in TypeScript:

npm install

Running the code below:

npm run numbers

gives the following results:

Functional Programming in TypeScript

Complements

Functional Programming in TypeScript

Let E and F be two sets. The relative complement of F in E, denoted by E F is the set of all elements which are members of E but not members of F.

Let Complement be the relative complement operation. Thus, the Complement operation can be implemented as follows in TypeScript:

npm run plane
Running the code below:
npm run fractals

gives the following results:

Functional Programming in TypeScript

Symmetric Difference

Functional Programming in TypeScript

Let E and F be two sets. The symmetric difference of E and F, denoted by E Δ F is the set of all elements which are members of either E and F but not in the intersection of E and F.

Let SymmetricDifference be the symmetric difference operation. Thus, the SymmetricDifference operation can be implemented in two ways in TypeScript. A trivial way is to use the union and complement operations as follows:

S'(x) = true if x is in S'
S'(x) = false if x is not in S'

Another way is to use the XOR binary operation as follows:

S'(a) = S'(b) = true
S'(c) = S'(d) = false

Running the code below:

S'(a) = S'(b) = true
S'(c) = S'(d) = false

gives the following results:

Functional Programming in TypeScript

Other Operations

This section presents other useful binary operations on sets.

Contains

Let Contains be the operation that checks whether or not an element is in a set. This operation is a function that takes as parameter an element and returns true if the element is in the set, false otherwise.

Thus, this operation is defined as follows in TypeScript:

type Set<T> = (x: T) => boolean

Therefore, running the code below:

npm install

gives the following result:

Functional Programming in TypeScript

Add

Let Add be the operation that adds an element to a set. This operation is a function that takes as parameter an element and adds it to the set.

Thus, this operation is defined as follows in TypeScript:

npm run numbers

Therefore, running the code below:

npm run plane

gives the following result:

Functional Programming in TypeScript

Remove

Let Remove be the operation that removes an element from a set. This operations is a function that takes as parameter an element and removes it from the set.

Thus, this operation is defined as follows in TypeScript:

npm run fractals

Therefore, running the code below:

S'(x) = true if x is in S'
S'(x) = false if x is not in S'

gives the following result:

Functional Programming in TypeScript

For Those Who Want To Go Further

You can see how easy we can do some algebra of sets in TypeScript through Functional Programming. In the previous sections was shown the most fundamental definitions. But, If you want to go further, you can think about:

  • Relations over sets
  • Abstract algebra, such as monoids, groups, fields, rings, K-vectorial spaces and so on
  • Inclusion-exclusion principle
  • Russell's paradox
  • Cantor's paradox
  • Dual vector space
  • Theorems and Corollaries

Euclidean Plane

In the previous section, the fundamental concepts on sets were implemented in TypeScript. In this section, we will practice the concepts implemented on the Euclidean plane.

Drawing a Disk

Functional Programming in TypeScript

A disk is a subset of a plane bounded by a circle. There are two types of disks. Closed disks which are disks that contain the points of the circle that constitutes its boundary, and Open disks which are disks that do not contain the points of the circle that constitutes its boundary.

In this section, we will set up the Characterstic function of the Closed disk and draw it in a HTML5 page.

To set up the Characterstic function, we first need a function that calculates the Euclidean Distance between two points in the plane. This function is implemented as follows:

S'(a) = S'(b) = true
S'(c) = S'(d) = false

where Point is defined below:

S'(a) = S'(b) = true
S'(c) = S'(d) = false

This formula is based on Pythagoras' Theorem.

Functional Programming in TypeScript

where c is the Euclidean distance, a² is (p1.X - p2.X)² and b² is (p1.Y - p2.Y)².

Let Disk be the Characteristic function of a closed disk. In algebra of sets, the definition of a closed disk in the reals set is as follows:

Functional Programming in TypeScript

where a and b are the coordinates of the center and R the radius.

Thus, the implementation of Disk in TypeScript is as follows:

npm install

In order to view the set in a HTML5 page, I decided to implement a function draw that draws a set in the Euclidean plane. I chose HTML5 and thus used the canvas element for drawing.

Thus, I've built the Euclidean plane illustrated below through the method draw.

Functional Programming in TypeScript

Below the implementation of the plane.

npm run numbers

In the draw function, a canvas having the same width and the same height as the Euclidean plane container is created. Then each point in pixels (x,y) of the canvas is replaced by a black point if it belongs to the set. xMin, xMax, yMin and yMax are the bounding values illustrated in the figure of the Euclidean plane above.

Running the code below:

npm run plane

where disk is the id of the canvas:

npm run fractals

gives the following result:

Functional Programming in TypeScript

Drawing Horizontal and Vertical Half-planes

Functional Programming in TypeScript

A horizontal or a vertical half-plane is either of the two subsets into which a plane divides the Euclidean space. A horizontal half-plane is either of the two subsets into which a plane divides the Euclidean space through a line perpendicular with the Y axis like in the figure above. A vertical half-plane is either of the two subsets into which a plane divides the Euclidean space through a line perpendicular with the X axis.

In this section, we will set up the Characteristic functions of the horizontal and vertical half-planes, draw them in a HTML5 page and see what we can do if we combine them with the disk subset.

Let HorizontalHalfPlane be the Characteristic function of a horizontal half-plane. The implementation of HorizontalHalfPlane in TypeScript is as follows:

S'(x) = true if x is in S'
S'(x) = false if x is not in S'

Thus, running the code below:

npm install

where hhp is the id of the canvas:

npm run numbers

gives the following result:

Functional Programming in TypeScript

Let VerticalHalfPlane be the Characteristic function of a vertical half-plane. The implementation of VerticalHalfPlane in TypeScript is as follows:

npm run plane
Thus, running the code below:
npm run fractals

where vhd is the id of the canvas:

S'(x) = true if x is in S'
S'(x) = false if x is not in S'

gives the following result:

Functional Programming in TypeScript

In the first section of the article, we set up basic binary operations on sets. Thus, by combining the intersection of a disk and a half-plane for example, we can draw the half-disk subset.

Therefore, running the sample below:

S'(a) = S'(b) = true
S'(c) = S'(d) = false

where hd is the id of the canvas:

S'(a) = S'(b) = true
S'(c) = S'(d) = false

gives the following result:

Functional Programming in TypeScript

Functions

This section presents functions on the sets in the Euclidean plane.

Translate

Functional Programming in TypeScript

Let translatePoint be the function that translates a point in the plane. In Euclidean geometry, translatePoint is a function that moves a given point a constant distance in a specified direction. Thus the implementation in TypeScript is as follows:

type Set<T> = (x: T) => boolean

where (deltax, deltay) is the constant vector of the translation.

Let translate be the function that translates a set in the plane. This function is simply implemented as follows in TypeScript:

Empty(x) = false if x is in E
Empty(x) = false if x is not in E
`translate` takes as parameters `deltax` which is the delta distance in the first Euclidean dimension and `deltay` which is the delta distance in the second Euclidean dimension. If a point _P (x, y)_ is translated in a set _S_, then its coordinates will change to _(x', y') = (x, delatx, y, deltay)_. Thus, the point _(x' - delatx, y' - deltay)_ will always belong to the set _S_. In set algebra, `translate` is called isomorph, in other words, the set of all translations forms the _translation group T_, which is isomorphic to the space itself. This explains the main logic of the function. Thus, running the code below in our HTML5 page:
const empty = () => (e: T) => false

where ep_op is the id of the canvas:

console.log('\nEmpty set:')
console.log('Is 7 in {}?', common.empty()(7))

gives the following result:

Functional Programming in TypeScript

Homothety

Functional Programming in TypeScript

Let scalePoint be the function that sends any point M to another point N such that the segment SN is on the same line as SM, but scaled by a factor λ. In algebra of sets, Scale is formulated as follows:

Functional Programming in TypeScript

Thus the implementation in TypeScript is as follows:

npm install

where (deltax, deltay) is the constant vector of the translation and (lambdax, lambday) is the lambda vector.

Let scale be the function that applies an homothety on a set in the plan. This function is simply implemented as follows in TypeScript:

npm run numbers

scale takes as parameters deltax which is the delta distance in the first Euclidean dimension, deltay which is the delta distance in the second Euclidean dimension and (lambdax, lambday) which is the constant factor vector λ. If a point P (x, y) is transformed through scale in a set S, then its coordinates will change to (x', y') = (lambdax * x, delatx, lambday * y, deltay). Thus, the point ((x'- delatx)/lambdax, (y' - deltay)/lambday) will always belong to the set S, If lambda is different from the vector 0, of course. In algebra of sets, scale is called isomorph, in other words, the set of all homotheties forms the Homothety group H, which is isomorphic to the space itself {0}. This explains the main logic of the function.

Thus, running the code below in our HTML5 page:

npm run plane

gives the following result:

Functional Programming in TypeScript

Rotate

Functional Programming in TypeScript

Let rotatePoint be the function that rotates a point with an angle θ. In matrix algebra, rotatePoint is formulated as follows:

Functional Programming in TypeScript

where (x', y') are the co-ordinates of the point after rotation, and the formula for x' and y' is as follows:

Functional Programming in TypeScript

The demonstration of this formula is very simple. Have a look at this rotation.

Functional Programming in TypeScript

Below the demonstration:

Functional Programming in TypeScript

Thus the implementation in TypeScript is as follows:

npm install

Let rotate be the function that applies a rotation on a set in the plane with the angle θ. This function is simply implemented as follows in TypeScript.

npm run numbers

rotate is a function that takes as parameter theta which is the angle of the rotation. If a point P (x, y) is transformed through rotate in a set S, then its coordinates will change to (x', y') = (x * cos(theta) - y * sin(theta), x * sin(theta), y * cos(theta)). Thus, the point (x' * cos(theta), y' * sin(theta), y' * cos(theta) - x' * sin(theta)) will always belong to the set S. In algebra of sets, rotate is called isomorph, in other words, the set of all rotations forms the Rotation group R, which is isomorphic to the space itself. This explains the main logic of the function.

Thus, running the code below in our HTML5 page:

npm run plane

gives the following result:

Functional Programming in TypeScript

For Those Who Want to Go Further

Very simple, isn't it? For those who want to go further, you can explore these:

  • Ellipse
  • Three-dimensional Euclidean space
  • Ellipsoide
  • Paraboloid
  • Hyperboloid
  • Spherical harmonics
  • Superellipsoid
  • Haumea
  • Homoeoid
  • Focaloid

Fractals

Functional Programming in TypeScript

Fractals are sets that have a fractal dimension that usually exceeds their topological dimension and may fall between the integers. For example, the Mandelbrot set is a fractal defined by a family of complex quadratic polynomials:

npm run fractals

where c is a complex. The Mandelbrot fractal is defined as the set of all points c such that the above sequence does not escape to infinity. In algebra of sets, this is formulated as follows:

Functional Programming in TypeScript

Fractals (abstract data type) can always be represented as follows in TypeScript:

S'(x) = true if x is in S'
S'(x) = false if x is not in S'

Complex Numbers and Drawing

In order to be able to draw fractals, I needed to manipulate Complex numbers. Thus, I created the Complex class below:

S'(a) = S'(b) = true
S'(c) = S'(d) = false

Mandelbrot Fractal

I created a Mandelbrot Fractal (abstract data type representation) P(z) = z^2 c that is available below.

npm install
In order to be able to draw _Complex_ numbers, I created a `ComplexPlane` class. Below is the implementation in TypeScript.
npm run numbers

Thus, running the code below:

npm run plane

where fractal is the id of the canvas:

npm run fractals

gives the following result:

Functional Programming in TypeScript

For Those Who Want to Go Further

For those who want to go further, you can explore these:

  • Newton Fractals
  • Julia Fractals
  • Other Fractals

That's it! I hope you enjoyed reading.

The above is the detailed content of Functional Programming in TypeScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn