•

0 likes•16 views

For functions that can be defined both as an instance of a right fold and as an instance of a left fold, one may be more efficient than the other. Let's look at the example of a function 'decimal' that converts a list of digits into the corresponding decimal number. Erratum: it has been pointed out that it is possible to define the zip function using a right fold (see slide 5).

Report

Share

Report

Share

Download to read offline

The Functional Programming Triad of Folding, Scanning and Iteration - a first...

The document discusses implementing various functional programming concepts like folding, scanning, and iteration to solve problems involving converting between digit sequences and integers. It provides examples in Scala and Haskell of using fold left to implement a digits-to-integer function and the iterate function to implement an integer-to-digits function. It also discusses using techniques like pipes in Scala and the $ operator in Haskell to improve readability by ordering function applications in the sequence they will be executed.

The Functional Programming Triad of Folding, Scanning and Iteration - a first...

This slide deck can work both as an aide mémoire (memory jogger), or as a first (not completely trivial) example of using left folds, left scans and iteration, to implement mathematical induction.
Errata: on almost half of the slides there is some minor typo or imperfection or in some cases a minor error and in one case, an omission. See a later version for corrections and some improvements.
(for best quality images, either download or view here: https://philipschwarz.dev/fpilluminated/?page_id=455)
Scala code for latest version: https://github.com/philipschwarz/fp-fold-scan-iterate-triad-a-first-example-scala

Real World Haskell: Lecture 6

This document summarizes a lecture about models of evaluation in Haskell. It discusses lazy evaluation and call-by-need evaluation in Haskell. It provides examples showing that expressions are not evaluated unless their values are needed. Common functions like map and fold can be written in terms of each other due to their shared structural transformation of lists. Both left and right folds are discussed, with right folds constructing nested applications and left folds avoiding this issue.

JBUG 11 - Scala For Java Programmers

Scala is a general purpose programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages, enabling Java and other programmers to be more productive." This session is an introduction of Scala for Java developers.
Presentation & Fetured Video Included.

Scala - where objects and functions meet

The document provides an overview of a two-day training course on Scala that covers topics like object orientation, functional programming, pattern matching, generics, traits, case classes, tuples, collections, concurrency, options and monads. The course aims to show how Scala combines object-oriented and functional programming approaches and provides examples of commonly used Scala features like classes, traits, pattern matching, generics and collections.

Real World Haskell: Lecture 2

The document discusses Haskell concepts including:
1) Pattern matching allows functions to handle different cases depending on the structure of input data, like matching empty and non-empty lists.
2) Guards allow selecting different code blocks based on Boolean conditions.
3) Combining pattern matching and guards allows for very expressive functions that concisely handle multiple cases.
4) Metasyntactic variables like (x:xs) follow conventions to bind pattern names and make code more readable.
5) Functions can match multiple patterns at once to handle different input structures.

Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4

(download for flawless image quality) Can a left fold ever work over an infinite list? What about a right fold? Find out.
Learn about the other two functions used by functional programmers to implement mathematical induction: iterating and scanning.
Learn about the limitations of the accumulator technique and about tupling, a technique that is the dual of the accumulator trick.

Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...

(download for flawless image quality) Can a left fold ever work over an infinite list? What about a right fold? Find out.
Learn about the other two functions used by functional programmers to implement mathematical induction: iterating and scanning.
Learn about the limitations of the accumulator technique and about tupling, a technique that is the dual of the accumulator trick.

The Functional Programming Triad of Folding, Scanning and Iteration - a first...

The document discusses implementing various functional programming concepts like folding, scanning, and iteration to solve problems involving converting between digit sequences and integers. It provides examples in Scala and Haskell of using fold left to implement a digits-to-integer function and the iterate function to implement an integer-to-digits function. It also discusses using techniques like pipes in Scala and the $ operator in Haskell to improve readability by ordering function applications in the sequence they will be executed.

The Functional Programming Triad of Folding, Scanning and Iteration - a first...

This slide deck can work both as an aide mémoire (memory jogger), or as a first (not completely trivial) example of using left folds, left scans and iteration, to implement mathematical induction.
Errata: on almost half of the slides there is some minor typo or imperfection or in some cases a minor error and in one case, an omission. See a later version for corrections and some improvements.
(for best quality images, either download or view here: https://philipschwarz.dev/fpilluminated/?page_id=455)
Scala code for latest version: https://github.com/philipschwarz/fp-fold-scan-iterate-triad-a-first-example-scala

Real World Haskell: Lecture 6

This document summarizes a lecture about models of evaluation in Haskell. It discusses lazy evaluation and call-by-need evaluation in Haskell. It provides examples showing that expressions are not evaluated unless their values are needed. Common functions like map and fold can be written in terms of each other due to their shared structural transformation of lists. Both left and right folds are discussed, with right folds constructing nested applications and left folds avoiding this issue.

JBUG 11 - Scala For Java Programmers

Scala is a general purpose programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages, enabling Java and other programmers to be more productive." This session is an introduction of Scala for Java developers.
Presentation & Fetured Video Included.

Scala - where objects and functions meet

The document provides an overview of a two-day training course on Scala that covers topics like object orientation, functional programming, pattern matching, generics, traits, case classes, tuples, collections, concurrency, options and monads. The course aims to show how Scala combines object-oriented and functional programming approaches and provides examples of commonly used Scala features like classes, traits, pattern matching, generics and collections.

Real World Haskell: Lecture 2

The document discusses Haskell concepts including:
1) Pattern matching allows functions to handle different cases depending on the structure of input data, like matching empty and non-empty lists.
2) Guards allow selecting different code blocks based on Boolean conditions.
3) Combining pattern matching and guards allows for very expressive functions that concisely handle multiple cases.
4) Metasyntactic variables like (x:xs) follow conventions to bind pattern names and make code more readable.
5) Functions can match multiple patterns at once to handle different input structures.

Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4

(download for flawless image quality) Can a left fold ever work over an infinite list? What about a right fold? Find out.
Learn about the other two functions used by functional programmers to implement mathematical induction: iterating and scanning.
Learn about the limitations of the accumulator technique and about tupling, a technique that is the dual of the accumulator trick.

Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...(download for flawless image quality) Can a left fold ever work over an infinite list? What about a right fold? Find out.
Learn about the other two functions used by functional programmers to implement mathematical induction: iterating and scanning.
Learn about the limitations of the accumulator technique and about tupling, a technique that is the dual of the accumulator trick.

Array

Arrays are data structures that store a collection of data values of the same type in consecutive memory locations that can be individually referenced by their numeric index. Different representations of arrays are possible including using a single block of memory or a collection of elements. Common operations on arrays include retrieving or storing elements by their index and traversing the entire array sequentially.

Teeing Up Python - Code Golf

This document summarizes Lee Sheng's presentation on code golfing and writing concise code. Some key points discussed include minimizing the number of characters or "strokes" in code, using features like defaultdicts, context managers, and list comprehensions to reduce strokes, and focusing on functional programming techniques like map, filter, and reduce to write shorter code that is still readable. The presentation emphasizes that writing concise code reduces cognitive load while still expressing the intent clearly.

Lecture 01 reals number system

The document discusses sets and operations involving sets of real numbers. It defines key sets such as the real numbers, rational numbers, integers, natural numbers, whole numbers, and irrational numbers. It also covers properties of real numbers like closure, commutativity, associativity, distributivity, identity, and inverse properties as they relate to addition and multiplication. Examples are provided to illustrate set notation and properties. The document contains exercises asking to identify which properties justify certain statements involving real number operations.

Python 04-ifelse-return-input-strings.pptx

This document discusses condition statements (if/else), functions that return values, user input using the input() function, logical operators, for loops used with strings, and string formatting. It provides examples of calculating total hours worked by employees, accessing characters in strings using indexes, common string methods like upper()/lower(), and basic cryptography techniques like the Caesar cipher. An exercise is given to write a program that encrypts a message using the Caesar cipher technique of rotating each letter by 3 positions.

Frp2016 3

Functions are treated as objects in Scala, with the function type A => B being an abbreviation for the class scala.Function1[A, B]. Functions are objects that have an apply method. Case classes implicitly define companion objects with apply methods, allowing constructor-like syntax. Pattern matching provides a way to generalize switch statements to class hierarchies. The for expression provides a cleaner syntax than higher-order functions like map and flatMap for working with collections, but compiles to calls to these functions. Types like Option and Try are examples of monads in Scala, making failure or missing data explicit in the type while hiding boilerplate code.

Complex function

This document is a report on Complex Variable & Numerical Method prepared by 5 students and guided by Miss. Chaitali Shah. It contains the following topics: complex numbers, complex variable, basic definitions, limits, continuity, differentiability, analytic functions, Cauchy-Riemann equations, harmonic functions, Milne-Thomson method, and applications of complex functions/variables in engineering. Examples are provided to illustrate several concepts.

Maths number system

The document discusses different number systems used in mathematics. It begins by explaining that a number system is defined by its base, or the number of unique symbols used to represent numbers. The most common system is decimal, which uses base-10. Other discussed systems include binary, octal, hexadecimal, and those used historically by cultures like the Babylonians. Rational and irrational numbers are also defined. Rational numbers can be written as fractions of integers, while irrational numbers cannot.

Map, Reduce and Filter in Swift

This document discusses functional programming concepts like map, reduce, and filter and provides Swift code examples for applying these concepts. It begins with an introduction to functional programming and key concepts. It then covers Swift basics like function types and passing functions. The bulk of the document explains and demonstrates map, reduce, filter and their uses on arrays and optionals in Swift. It concludes with suggestions for further functional programming topics and resources.

23UCACC11 Python Programming (MTNC) (BCA)

This document provides an overview of key Python concepts including numbers, strings, variables, lists, tuples, dictionaries, and sets. It defines each concept and provides examples. Numbers discusses integer, float, and complex data types. Strings covers string operations like accessing characters, concatenation, formatting and methods. Variables explains variable naming rules and scopes. Lists demonstrates accessing, modifying, and sorting list elements. Tuples describes immutable ordered collections. Dictionaries defines storing and accessing data via keys and values. Sets introduces unordered unique element collections.

Lists.pptx

This document provides an overview of lists in Python. It defines what a list is, how to create and access list elements, and common list operations like slicing, concatenation, and modification. It also covers list methods such as append(), insert(), remove(), and sort(). The document discusses lists as mutable objects and the concepts of aliasing and passing lists to functions.

Scala. Introduction to FP. Monads

This presentation takes you on a functional programming journey, it starts from basic Scala programming language design concepts and leads to a concept of Monads, how some of them designed in Scala and what is the purpose of them

Python Lecture 11

This document discusses tuples and sets in Python. It defines tuples as immutable sequences that can contain heterogeneous data types. Tuples can be indexed and sliced but not modified. Sets are unordered collections of unique and immutable elements. Common set operations include union, intersection, difference, and symmetric difference.

Monad Fact #4

Download for flawless quality (slides viewed online look a bit grainy and out of focus). A monad is an implementation of one of the minimal sets of monadic combinators, satisfying the laws of associativity and identity - see how compositional responsibilities are distributed in each combinator set

Ch8b

The document discusses several advanced intermediate code generation techniques used in compilers, including:
1) Reusing temporary variable names to avoid using new temps whenever possible.
2) Addressing elements in one-dimensional and multi-dimensional arrays using base addresses and calculating offsets.
3) Translating logical, relational, and Boolean expressions using three-address code with temporary variables to store intermediate values.

Scala by Luc Duponcheel

Scala is a multi-paradigm programming language that supports functional, object-oriented and imperative programming paradigms. The document discusses Scala's support for types, expressions, objects, functions, and provides examples of using Scala for expressions, functions, control structures, patterns, spaces and actors.

7. basics

As part of the GSP’s capacity development and improvement programme, FAO/GSP have organised a one week training in Izmir, Turkey. The main goal of the training was to increase the capacity of Turkey on digital soil mapping, new approaches on data collection, data processing and modelling of soil organic carbon. This 5 day training is titled ‘’Training on Digital Soil Organic Carbon Mapping’’ was held in IARTC - International Agricultural Research and Education Center in Menemen, Izmir on 20-25 August, 2017.

iRODS Rule Language Cheat Sheet

This document provides a cheat sheet overview of key concepts in the IRODS rule language, including numeric and string literals, arithmetic and comparison operators, functions for strings, lists, tuples, if/else statements, foreach loops, defining functions and rules, handling errors, and inductive data types. It describes syntax for defining data types using constructors, and using pattern matching to define functions over data types.

Understanding the "Chain Rule" for Derivatives by Deriving Your Own Version

Because the Chain Rule can confuse students as much as it helps them solve real problems, we put ourselves in the shoes of the mathematicians who derived it, so that students may understand the motivation for the rule; its limitations; and why textbooks present it in its customary form. We begin by finding the derivative of sin2x without using the Chain Rule. That exercise, having shown that even a comparatively simple compound function can be bothersome to differentiate using the definition of the derivative as a limit, provides the motivation for developing our own formula for the derivative of the general compound function g[f(x)]. In the course of that development, we see why the function f must be continuous at any value of x to which the formula is applied. We finish by comparing our formula to that which is commonly given.

Introduction to Functional Programming with Scala

The document discusses the benefits of functional programming including less code, immutability, concurrency and distribution, pattern matching, and higher-order functions. It provides code examples in Scala demonstrating each of these benefits. Specifically, it shows how functional programming can reduce lines of code for calculating factorials, enable concurrency through futures and distribution through parallelization, utilize pattern matching to extract values from data structures and match on types, and leverage higher-order functions like map and fold to operate on collections in a declarative way.

functions

The document discusses functions and algorithms. It defines what a function is and provides examples. It also discusses different types of functions such as one-to-one, onto, and inverse functions. The document then discusses algorithms and complexity analysis. It provides examples of linear search algorithms and analyzes their worst case and average case time complexities.

Folding Cheat Sheet #6 - sixth in a series

Left and right folds and tail recursion.

Folding Cheat Sheet #5 - fifth in a series

Folding a list right and left using Cons and Nil results in the identity and reverse functions.

Array

Arrays are data structures that store a collection of data values of the same type in consecutive memory locations that can be individually referenced by their numeric index. Different representations of arrays are possible including using a single block of memory or a collection of elements. Common operations on arrays include retrieving or storing elements by their index and traversing the entire array sequentially.

Teeing Up Python - Code Golf

This document summarizes Lee Sheng's presentation on code golfing and writing concise code. Some key points discussed include minimizing the number of characters or "strokes" in code, using features like defaultdicts, context managers, and list comprehensions to reduce strokes, and focusing on functional programming techniques like map, filter, and reduce to write shorter code that is still readable. The presentation emphasizes that writing concise code reduces cognitive load while still expressing the intent clearly.

Lecture 01 reals number system

The document discusses sets and operations involving sets of real numbers. It defines key sets such as the real numbers, rational numbers, integers, natural numbers, whole numbers, and irrational numbers. It also covers properties of real numbers like closure, commutativity, associativity, distributivity, identity, and inverse properties as they relate to addition and multiplication. Examples are provided to illustrate set notation and properties. The document contains exercises asking to identify which properties justify certain statements involving real number operations.

Python 04-ifelse-return-input-strings.pptx

This document discusses condition statements (if/else), functions that return values, user input using the input() function, logical operators, for loops used with strings, and string formatting. It provides examples of calculating total hours worked by employees, accessing characters in strings using indexes, common string methods like upper()/lower(), and basic cryptography techniques like the Caesar cipher. An exercise is given to write a program that encrypts a message using the Caesar cipher technique of rotating each letter by 3 positions.

Frp2016 3

Functions are treated as objects in Scala, with the function type A => B being an abbreviation for the class scala.Function1[A, B]. Functions are objects that have an apply method. Case classes implicitly define companion objects with apply methods, allowing constructor-like syntax. Pattern matching provides a way to generalize switch statements to class hierarchies. The for expression provides a cleaner syntax than higher-order functions like map and flatMap for working with collections, but compiles to calls to these functions. Types like Option and Try are examples of monads in Scala, making failure or missing data explicit in the type while hiding boilerplate code.

Complex function

This document is a report on Complex Variable & Numerical Method prepared by 5 students and guided by Miss. Chaitali Shah. It contains the following topics: complex numbers, complex variable, basic definitions, limits, continuity, differentiability, analytic functions, Cauchy-Riemann equations, harmonic functions, Milne-Thomson method, and applications of complex functions/variables in engineering. Examples are provided to illustrate several concepts.

Maths number system

The document discusses different number systems used in mathematics. It begins by explaining that a number system is defined by its base, or the number of unique symbols used to represent numbers. The most common system is decimal, which uses base-10. Other discussed systems include binary, octal, hexadecimal, and those used historically by cultures like the Babylonians. Rational and irrational numbers are also defined. Rational numbers can be written as fractions of integers, while irrational numbers cannot.

Map, Reduce and Filter in Swift

This document discusses functional programming concepts like map, reduce, and filter and provides Swift code examples for applying these concepts. It begins with an introduction to functional programming and key concepts. It then covers Swift basics like function types and passing functions. The bulk of the document explains and demonstrates map, reduce, filter and their uses on arrays and optionals in Swift. It concludes with suggestions for further functional programming topics and resources.

23UCACC11 Python Programming (MTNC) (BCA)

This document provides an overview of key Python concepts including numbers, strings, variables, lists, tuples, dictionaries, and sets. It defines each concept and provides examples. Numbers discusses integer, float, and complex data types. Strings covers string operations like accessing characters, concatenation, formatting and methods. Variables explains variable naming rules and scopes. Lists demonstrates accessing, modifying, and sorting list elements. Tuples describes immutable ordered collections. Dictionaries defines storing and accessing data via keys and values. Sets introduces unordered unique element collections.

Lists.pptx

This document provides an overview of lists in Python. It defines what a list is, how to create and access list elements, and common list operations like slicing, concatenation, and modification. It also covers list methods such as append(), insert(), remove(), and sort(). The document discusses lists as mutable objects and the concepts of aliasing and passing lists to functions.

Scala. Introduction to FP. Monads

This presentation takes you on a functional programming journey, it starts from basic Scala programming language design concepts and leads to a concept of Monads, how some of them designed in Scala and what is the purpose of them

Python Lecture 11

This document discusses tuples and sets in Python. It defines tuples as immutable sequences that can contain heterogeneous data types. Tuples can be indexed and sliced but not modified. Sets are unordered collections of unique and immutable elements. Common set operations include union, intersection, difference, and symmetric difference.

Monad Fact #4

Download for flawless quality (slides viewed online look a bit grainy and out of focus). A monad is an implementation of one of the minimal sets of monadic combinators, satisfying the laws of associativity and identity - see how compositional responsibilities are distributed in each combinator set

Ch8b

The document discusses several advanced intermediate code generation techniques used in compilers, including:
1) Reusing temporary variable names to avoid using new temps whenever possible.
2) Addressing elements in one-dimensional and multi-dimensional arrays using base addresses and calculating offsets.
3) Translating logical, relational, and Boolean expressions using three-address code with temporary variables to store intermediate values.

Scala by Luc Duponcheel

Scala is a multi-paradigm programming language that supports functional, object-oriented and imperative programming paradigms. The document discusses Scala's support for types, expressions, objects, functions, and provides examples of using Scala for expressions, functions, control structures, patterns, spaces and actors.

7. basics

As part of the GSP’s capacity development and improvement programme, FAO/GSP have organised a one week training in Izmir, Turkey. The main goal of the training was to increase the capacity of Turkey on digital soil mapping, new approaches on data collection, data processing and modelling of soil organic carbon. This 5 day training is titled ‘’Training on Digital Soil Organic Carbon Mapping’’ was held in IARTC - International Agricultural Research and Education Center in Menemen, Izmir on 20-25 August, 2017.

iRODS Rule Language Cheat Sheet

This document provides a cheat sheet overview of key concepts in the IRODS rule language, including numeric and string literals, arithmetic and comparison operators, functions for strings, lists, tuples, if/else statements, foreach loops, defining functions and rules, handling errors, and inductive data types. It describes syntax for defining data types using constructors, and using pattern matching to define functions over data types.

Understanding the "Chain Rule" for Derivatives by Deriving Your Own Version

Because the Chain Rule can confuse students as much as it helps them solve real problems, we put ourselves in the shoes of the mathematicians who derived it, so that students may understand the motivation for the rule; its limitations; and why textbooks present it in its customary form. We begin by finding the derivative of sin2x without using the Chain Rule. That exercise, having shown that even a comparatively simple compound function can be bothersome to differentiate using the definition of the derivative as a limit, provides the motivation for developing our own formula for the derivative of the general compound function g[f(x)]. In the course of that development, we see why the function f must be continuous at any value of x to which the formula is applied. We finish by comparing our formula to that which is commonly given.

Introduction to Functional Programming with Scala

The document discusses the benefits of functional programming including less code, immutability, concurrency and distribution, pattern matching, and higher-order functions. It provides code examples in Scala demonstrating each of these benefits. Specifically, it shows how functional programming can reduce lines of code for calculating factorials, enable concurrency through futures and distribution through parallelization, utilize pattern matching to extract values from data structures and match on types, and leverage higher-order functions like map and fold to operate on collections in a declarative way.

functions

The document discusses functions and algorithms. It defines what a function is and provides examples. It also discusses different types of functions such as one-to-one, onto, and inverse functions. The document then discusses algorithms and complexity analysis. It provides examples of linear search algorithms and analyzes their worst case and average case time complexities.

Array

Array

Teeing Up Python - Code Golf

Teeing Up Python - Code Golf

Lecture 01 reals number system

Lecture 01 reals number system

Python 04-ifelse-return-input-strings.pptx

Python 04-ifelse-return-input-strings.pptx

Frp2016 3

Frp2016 3

Complex function

Complex function

Maths number system

Maths number system

Map, Reduce and Filter in Swift

Map, Reduce and Filter in Swift

23UCACC11 Python Programming (MTNC) (BCA)

23UCACC11 Python Programming (MTNC) (BCA)

Lists.pptx

Lists.pptx

Scala. Introduction to FP. Monads

Scala. Introduction to FP. Monads

Python Lecture 11

Python Lecture 11

Monad Fact #4

Monad Fact #4

Ch8b

Ch8b

Scala by Luc Duponcheel

Scala by Luc Duponcheel

7. basics

7. basics

iRODS Rule Language Cheat Sheet

iRODS Rule Language Cheat Sheet

Understanding the "Chain Rule" for Derivatives by Deriving Your Own Version

Understanding the "Chain Rule" for Derivatives by Deriving Your Own Version

Introduction to Functional Programming with Scala

Introduction to Functional Programming with Scala

functions

functions

Folding Cheat Sheet #6 - sixth in a series

Left and right folds and tail recursion.

Folding Cheat Sheet #5 - fifth in a series

Folding a list right and left using Cons and Nil results in the identity and reverse functions.

Hand Rolled Applicative User ValidationCode Kata

Could you use a simple piece of Scala validation code (granted, a very simplistic one too!) that you can rewrite, now and again, to refresh your basic understanding of Applicative operators <*>, <*, *>?
The goal is not to write perfect code showcasing validation, but rather, to provide a small, rough-and ready exercise to reinforce your muscle-memory.
Despite its grandiose-sounding title, this deck consists of just three slides showing the Scala 3 code to be rewritten whenever the details of the operators begin to fade away.
The code is my rough and ready translation of a Haskell user-validation program found in a book called Finding Success (and Failure) in Haskell - Fall in love with applicative functors.

A Sighting of filterA in Typelevel Rite of Passage

Slide deck home: https://fpilluminated.com/deck/220

Direct Style Effect Systems -The Print[A] Example- A Comprehension Aid

The subject of this deck is the small Print[A] program in the following blog post by Noel Welsh: https://www.inner-product.com/posts/direct-style-effects/.
Keywords: "direct-style", "context function", "context functions", "algebraic effect", "algebraic effects", "scala", "effect system", "effect systems", "effect", "side effect", "composition", "fp", "functional programming"

Folding Cheat Sheet #3 - third in a series

This document summarizes the universal property of fold, which states that for finite lists the fold function is the unique function that satisfies its defining recursive equations. It provides examples of how common list functions like sum, product, length, concatenation (⧺) can be defined in terms of fold. It also notes that the universal property can be generalized to handle partial and infinite lists. Finally, it states that map, filter and fold form the "triad" or basic building blocks of functional programming.

Folding Cheat Sheet #2 - second in a series

This document provides definitions and examples of foldr and foldl functions in functional programming. Foldr recursively applies a function from right to left, associating at each step. Foldl recursively applies a function from left to right, associating at each step. Examples are given applying foldr and foldl to a list with elements a0 through a3, using a function f and initial value b. Programmatic and mathematical definitions of foldr and foldl are also presented.

Folding Cheat Sheet #1 - first in a series

This document provides examples of using fold functions to define recursive functions over natural numbers (Nat) and lists. It shows common patterns for defining recursive functions over Nat using foldn and over lists using foldr. Three examples are given of functions defined over Nat using foldn: addition, multiplication, and exponentiation. Three examples are also given of functions defined over lists using foldr: sum, length, and append.

Scala Left Fold Parallelisation- Three Approaches

Slide deck home: http://fpilluminated.com/assets/scala-left-fold-parallelisation-three-approaches.html

Tagless Final Encoding - Algebras and Interpreters and also Programs

Tagless Final Encoding - Algebras and Interpreters and also Programs - An introduction, through the work of Gabriel Volpe.
Slide deck home: http://fpilluminated.com/assets/tagless-final-encoding-algebras-interpreters-and-programs.html

Fusing Transformations of Strict Scala Collections with Views

Slide deck home: http://fpilluminated.com/assets/fusing-transformations-of-strict-scala-collections-with-views.html

A sighting of traverse_ function in Practical FP in Scala

Slide deck home: http://fpilluminated.com/assets/sighting-of-scala-cats-traverse_-function-in-practical-fp-in-scala.html

A sighting of traverseFilter and foldMap in Practical FP in Scala

Slide deck home: http://fpilluminated.com/assets/sighting-of-scala-cats-traverseFilter-and-foldMap-in-practical-fp-in-scala.html.
Download PDF for perfect image quality.

A sighting of sequence function in Practical FP in Scala

Slide deck home: http://fpilluminated.com/assets/sighting-of-scala-cats-sequence-function-in-practical-fp-in-scala.html.
Download PDF for perfect image quality.

N-Queens Combinatorial Puzzle meets Cats

This talk was presented on Aug 3rd 2023 during the Scala in the City event a ITV in London https://www.meetup.com/scala-in-the-city/events/292844968/
Visit the following for a description, slideshow, all slides with transcript, pdf, github repo, and eventually a video recording: http://fpilluminated.com/assets/n-queens-combinatorial-puzzle-meets-cats.html
At the centre of this talk is the N-Queens combinatorial puzzle. The reason why this puzzle features in the Scala book and functional programming course by Martin Odersky (the language’s creator), is that such puzzles are a particularly suitable application area of 'for comprehensions'.
We’ll start by (re)acquainting ourselves with the puzzle, and seeing the role played in it by permutations. Next, we’ll see how, when wanting to visualise candidate puzzle solutions, Cats’ monoidal functions fold and foldMap are a great fit for combining images.
While we are all very familiar with the triad providing the bread, butter and jam of functional programming, i.e. map, filter and fold, not everyone knows about the corresponding functions in Cats’ monadic variant of the triad, i.e. mapM, filterM and foldM, which we are going to learn about next.
As is often the case in functional programming, the traverse function makes an appearance, and we shall grab the opportunity to point out the symmetry that exists in the interrelation of flatMap / foldMap / traverse and flatten / fold / sequence.
Armed with an understanding of foldM, we then look at how such a function can be used to implement an iterative algorithm for the N-Queens puzzle.
The talk ends by pointing out that the iterative algorithm is smarter than the recursive one, because it ‘remembers’ where it has already placed previous queens.

Kleisli composition, flatMap, join, map, unit - implementation and interrelat...

Kleisli composition, flatMap, join, map, unit. A study/memory aid, to help learn/recall their implementation/interrelation.
Version 2, updated for Scala 3

The aggregate function - from sequential and parallel folds to parallel aggre...

The aggregate function - from sequential and parallel folds to parallel aggregation - Java and Scala

Nat, List and Option Monoids -from scratch -Combining and Folding -an example

Nat, List and Option Monoids, from scratch. Combining and Folding: an example.
This is a new version of the original which has some cosmetic changes and a new 7th slide which only differs from slide 6 in that it defines the fold function in terms of the foldRight function.
Code: https://github.com/philipschwarz/nat-list-and-option-monoids-from-scratch-combining-and-folding-an-example

Nat, List and Option Monoids -from scratch -Combining and Folding -an example

Nat, List and Option Monoids, from scratch. Combining and Folding: an example.
Code: https://github.com/philipschwarz/nat-list-and-option-monoids-from-scratch-combining-and-folding-an-example

The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...

When I posted the deck for Part 1 to the Scala users forum, Odd Möller linked to a paper titled "The Genuine Sieve of Eratosthenes", which speaks of the Unfaithful Sieve.
Part 2 is based on that paper and on Richard Bird's faithful Haskell implementation of the Sieve, which we translate into Scala.
Scala code for Richard Bird's infinite primes Haskell program: https://github.com/philipschwarz/sieve-of-eratosthenes-part-2-scala

Folding Cheat Sheet #6 - sixth in a series

Folding Cheat Sheet #6 - sixth in a series

Folding Cheat Sheet #5 - fifth in a series

Folding Cheat Sheet #5 - fifth in a series

Hand Rolled Applicative User ValidationCode Kata

Hand Rolled Applicative User ValidationCode Kata

A Sighting of filterA in Typelevel Rite of Passage

A Sighting of filterA in Typelevel Rite of Passage

Direct Style Effect Systems -The Print[A] Example- A Comprehension Aid

Direct Style Effect Systems -The Print[A] Example- A Comprehension Aid

Folding Cheat Sheet #3 - third in a series

Folding Cheat Sheet #3 - third in a series

Folding Cheat Sheet #2 - second in a series

Folding Cheat Sheet #2 - second in a series

Folding Cheat Sheet #1 - first in a series

Folding Cheat Sheet #1 - first in a series

Scala Left Fold Parallelisation- Three Approaches

Scala Left Fold Parallelisation- Three Approaches

Tagless Final Encoding - Algebras and Interpreters and also Programs

Tagless Final Encoding - Algebras and Interpreters and also Programs

Fusing Transformations of Strict Scala Collections with Views

Fusing Transformations of Strict Scala Collections with Views

A sighting of traverse_ function in Practical FP in Scala

A sighting of traverse_ function in Practical FP in Scala

A sighting of traverseFilter and foldMap in Practical FP in Scala

A sighting of traverseFilter and foldMap in Practical FP in Scala

A sighting of sequence function in Practical FP in Scala

A sighting of sequence function in Practical FP in Scala

N-Queens Combinatorial Puzzle meets Cats

N-Queens Combinatorial Puzzle meets Cats

Kleisli composition, flatMap, join, map, unit - implementation and interrelat...

Kleisli composition, flatMap, join, map, unit - implementation and interrelat...

The aggregate function - from sequential and parallel folds to parallel aggre...

The aggregate function - from sequential and parallel folds to parallel aggre...

Nat, List and Option Monoids -from scratch -Combining and Folding -an example

Nat, List and Option Monoids -from scratch -Combining and Folding -an example

Nat, List and Option Monoids -from scratch -Combining and Folding -an example

Nat, List and Option Monoids -from scratch -Combining and Folding -an example

The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...

The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...

Upturn India Technologies - Web development company in Nashik

Nashik's top web development company, Upturn India Technologies, crafts innovative digital solutions for your success. Partner with us and achieve your goals

WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...

Vector databases are transforming how we handle data, allowing us to search through text, images, and audio by converting them into vectors. Today, we'll dive into the basics of this exciting technology and discuss its potential to revolutionize our next-generation AI applications. We'll examine typical uses for these databases and the essential tools
developers need. Plus, we'll zoom in on the advanced capabilities of vector search and semantic caching in Java, showcasing these through a live demo with Redis libraries. Get ready to see how these powerful tools can change the game!

Superpower Your Apache Kafka Applications Development with Complementary Open...

Kafka Summit talk (Bangalore, India, May 2, 2024, https://events.bizzabo.com/573863/agenda/session/1300469 )
Many Apache Kafka use cases take advantage of Kafka’s ability to integrate multiple heterogeneous systems for stream processing and real-time machine learning scenarios. But Kafka also exists in a rich ecosystem of related but complementary stream processing technologies and tools, particularly from the open-source community. In this talk, we’ll take you on a tour of a selection of complementary tools that can make Kafka even more powerful. We’ll focus on tools for stream processing and querying, streaming machine learning, stream visibility and observation, stream meta-data, stream visualisation, stream development including testing and the use of Generative AI and LLMs, and stream performance and scalability. By the end you will have a good idea of the types of Kafka “superhero” tools that exist, which are my favourites (and what superpowers they have), and how they combine to save your Kafka applications development universe from swamploads of data stagnation monsters!

Computer Science & Engineering VI Sem- New Syllabus.pdf

Uttarakhand board of technical education

Mobile App Development Company In Noida | Drona Infotech

React.js, a JavaScript library developed by Facebook, has gained immense popularity for building user interfaces, especially for single-page applications. Over the years, React has evolved and expanded its capabilities, becoming a preferred choice for mobile app development. This article will explore why React.js is an excellent choice for the Best Mobile App development company in Noida.
Visit Us For Information: https://www.linkedin.com/pulse/what-makes-reactjs-stand-out-mobile-app-development-rajesh-rai-pihvf/

How GenAI Can Improve Supplier Performance Management.pdf

Data Collection and Analysis with GenAI enables organizations to gather, analyze, and visualize vast amounts of supplier data, identifying key performance indicators and trends. Predictive analytics forecast future supplier performance, mitigating risks and seizing opportunities. Supplier segmentation allows for tailored management strategies, optimizing resource allocation. Automated scorecards and reporting provide real-time insights, enhancing transparency and tracking progress. Collaboration is fostered through GenAI-powered platforms, driving continuous improvement. NLP analyzes unstructured feedback, uncovering deeper insights into supplier relationships. Simulation and scenario planning tools anticipate supply chain disruptions, supporting informed decision-making. Integration with existing systems enhances data accuracy and consistency. McKinsey estimates GenAI could deliver $2.6 trillion to $4.4 trillion in economic benefits annually across industries, revolutionizing procurement processes and delivering significant ROI.

Orca: Nocode Graphical Editor for Container Orchestration

Tool demo on CEDI/SISTEDES/JISBD2024 at A Coruña, Spain. 2024.06.18
"Orca: Nocode Graphical Editor for Container Orchestration"
by Pedro J. Molina PhD. from Metadev

42 Ways to Generate Real Estate Leads - Sellxpert

Generate hot real estate leads with these simple strategies. 42 innovative ways to attract clients in the real estate industry.

Transforming Product Development using OnePlan To Boost Efficiency and Innova...

Ready to overcome challenges and drive innovation in your organization? Join us in our upcoming webinar where we discuss how to combat resource limitations, scope creep, and the difficulties of aligning your projects with strategic goals. Discover how OnePlan can revolutionize your product development processes, helping your team to innovate faster, manage resources more effectively, and deliver exceptional results.

一比一原版(USF毕业证)旧金山大学毕业证如何办理

USF硕士毕业证成绩单【微信95270640】一比一伪造旧金山大学文凭@假冒USF毕业证成绩单+Q微信95270640办理USF学位证书@仿造USF毕业文凭证书@购买旧金山大学毕业证成绩单USF真实使馆认证/真实留信认证回国人员证明
#一整套旧金山大学文凭证件办理#—包含旧金山大学旧金山大学本科毕业证成绩单学历认证|使馆认证|归国人员证明|教育部认证|留信网认证永远存档教育部学历学位认证查询办理国外文凭国外学历学位认证#我们提供全套办理服务。
一整套留学文凭证件服务：
一：旧金山大学旧金山大学本科毕业证成绩单毕业证 #成绩单等全套材料从防伪到印刷水印底纹到钢印烫金
二：真实使馆认证（留学人员回国证明）使馆存档
三：真实教育部认证教育部存档教育部留服网站永久可查
四：留信认证留学生信息网站永久可查
国外毕业证学位证成绩单办理方法：
1客户提供办理旧金山大学旧金山大学本科毕业证成绩单信息：姓名生日专业学位毕业时间等（如信息不确定可以咨询顾问：我们有专业老师帮你查询）；
2开始安排制作毕业证成绩单电子图；
3毕业证成绩单电子版做好以后发送给您确认；
4毕业证成绩单电子版您确认信息无误之后安排制作成品；
5成品做好拍照或者视频给您确认；
6快递给客户（国内顺丰国外DHLUPS等快读邮寄）。
教育部文凭学历认证认证的用途：
如果您计划在国内发展那么办理国内教育部认证是必不可少的。事业性用人单位如银行国企公务员在您应聘时都会需要您提供这个认证。其他私营 #外企企业无需提供！办理教育部认证所需资料众多且烦琐所有材料您都必须提供原件我们凭借丰富的经验帮您快速整合材料让您少走弯路。
实体公司专业为您服务如有需要请联系我: 微信95270640奈一次次令他失望山娃今年岁上五年级识得很多字从走出小屋开始山娃就知道父亲的家和工地共有一个很动听的名字——天河工地的底层空空荡荡很宽阔很凉爽在地上铺上报纸和水泥袋父亲和工人们中午全睡在地上地面坑坑洼洼山娃曾多次绊倒过也曾有长铁钉穿透凉鞋刺在脚板上但山娃不怕工地上也常有五六个从乡下来的小学生他们的父母亲也是高楼上的建筑工人小伙伴来自不同省份都操着带有浓重口音的普通话可不知为啥山娃不仅很快与他们熟识了

bgiolcb

bgiolcb

Stork Product Overview: An AI-Powered Autonomous Delivery Fleet

Imagine a world where instead of blue and brown trucks dropping parcels on our porches, a buzzing drove of drones delivered our goods. Now imagine those drones are controlled by 3 purpose-built AI designed to ensure all packages were delivered as quickly and as economically as possible That's what Stork is all about.

Building API data products on top of your real-time data infrastructure

This talk and live demonstration will examine how Confluent and Gravitee.io integrate to unlock value from streaming data through API products.
You will learn how data owners and API providers can document, secure data products on top of Confluent brokers, including schema validation, topic routing and message filtering.
You will also see how data and API consumers can discover and subscribe to products in a developer portal, as well as how they can integrate with Confluent topics through protocols like REST, Websockets, Server-sent Events and Webhooks.
Whether you want to monetize your real-time data, enable new integrations with partners, or provide self-service access to topics through various protocols, this webinar is for you!

The Rising Future of CPaaS in the Middle East 2024

Explore "The Rising Future of CPaaS in the Middle East in 2024" with this comprehensive PPT presentation. Discover how Communication Platforms as a Service (CPaaS) is transforming communication across various sectors in the Middle East.

What is Continuous Testing in DevOps - A Definitive Guide.pdf

Once an overlooked aspect, continuous testing has become indispensable for enterprises striving to accelerate application delivery and reduce business impacts. According to a Statista report, 31.3% of global enterprises have embraced continuous integration and deployment within their DevOps, signaling a pervasive trend toward hastening release cycles.

Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...

Closing talk for the Performance Engineering track at Community Over Code EU (Bratislava, Slovakia, June 5 2024) https://eu.communityovercode.org/sessions/2024/why-apache-kafka-clusters-are-like-galaxies-and-other-cosmic-kafka-quandaries-explored/ Instaclustr (now part of NetApp) manages 100s of Apache Kafka clusters of many different sizes, for a variety of use cases and customers. For the last 7 years I’ve been focused outwardly on exploring Kafka application development challenges, but recently I decided to look inward and see what I could discover about the performance, scalability and resource characteristics of the Kafka clusters themselves. Using a suite of Performance Engineering techniques, I will reveal some surprising discoveries about cosmic Kafka mysteries in our data centres, related to: cluster sizes and distribution (using Zipf’s Law), horizontal vs. vertical scalability, and predicting Kafka performance using metrics, modelling and regression techniques. These insights are relevant to Kafka developers and operators.

美洲杯赔率投注网【网址🎉3977·EE🎉】

美洲杯赔率投注网【网址🎉3977·EE🎉】

Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx

Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0

Streamlining End-to-End Testing Automation

Streamlining End-to-End Testing Automation with Azure DevOps Build & Release Pipelines
Automating end-to-end (e2e) test for Android and iOS native apps, and web apps, within Azure build and release pipelines, poses several challenges. This session dives into the key challenges and the repeatable solutions implemented across multiple teams at a leading Indian telecom disruptor, renowned for its affordable 4G/5G services, digital platforms, and broadband connectivity.
Challenge #1. Ensuring Test Environment Consistency: Establishing a standardized test execution environment across hundreds of Azure DevOps agents is crucial for achieving dependable testing results. This uniformity must seamlessly span from Build pipelines to various stages of the Release pipeline.
Challenge #2. Coordinated Test Execution Across Environments: Executing distinct subsets of tests using the same automation framework across diverse environments, such as the build pipeline and specific stages of the Release Pipeline, demands flexible and cohesive approaches.
Challenge #3. Testing on Linux-based Azure DevOps Agents: Conducting tests, particularly for web and native apps, on Azure DevOps Linux agents lacking browser or device connectivity presents specific challenges in attaining thorough testing coverage.
This session delves into how these challenges were addressed through:
1. Automate the setup of essential dependencies to ensure a consistent testing environment.
2. Create standardized templates for executing API tests, API workflow tests, and end-to-end tests in the Build pipeline, streamlining the testing process.
3. Implement task groups in Release pipeline stages to facilitate the execution of tests, ensuring consistency and efficiency across deployment phases.
4. Deploy browsers within Docker containers for web application testing, enhancing portability and scalability of testing environments.
5. Leverage diverse device farms dedicated to Android, iOS, and browser testing to cover a wide range of platforms and devices.
6. Integrate AI technology, such as Applitools Visual AI and Ultrafast Grid, to automate test execution and validation, improving accuracy and efficiency.
7. Utilize AI/ML-powered central test automation reporting server through platforms like reportportal.io, providing consolidated and real-time insights into test performance and issues.
These solutions not only facilitate comprehensive testing across platforms but also promote the principles of shift-left testing, enabling early feedback, implementing quality gates, and ensuring repeatability. By adopting these techniques, teams can effectively automate and execute tests, accelerating software delivery while upholding high-quality standards across Android, iOS, and web applications.

Upturn India Technologies - Web development company in Nashik

Upturn India Technologies - Web development company in Nashik

WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...

WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...

Superpower Your Apache Kafka Applications Development with Complementary Open...

Superpower Your Apache Kafka Applications Development with Complementary Open...

Computer Science & Engineering VI Sem- New Syllabus.pdf

Computer Science & Engineering VI Sem- New Syllabus.pdf

Mobile App Development Company In Noida | Drona Infotech

Mobile App Development Company In Noida | Drona Infotech

How GenAI Can Improve Supplier Performance Management.pdf

How GenAI Can Improve Supplier Performance Management.pdf

Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx

Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx

Orca: Nocode Graphical Editor for Container Orchestration

Orca: Nocode Graphical Editor for Container Orchestration

42 Ways to Generate Real Estate Leads - Sellxpert

42 Ways to Generate Real Estate Leads - Sellxpert

Transforming Product Development using OnePlan To Boost Efficiency and Innova...

Transforming Product Development using OnePlan To Boost Efficiency and Innova...

一比一原版(USF毕业证)旧金山大学毕业证如何办理

一比一原版(USF毕业证)旧金山大学毕业证如何办理

bgiolcb

bgiolcb

Stork Product Overview: An AI-Powered Autonomous Delivery Fleet

Stork Product Overview: An AI-Powered Autonomous Delivery Fleet

Building API data products on top of your real-time data infrastructure

Building API data products on top of your real-time data infrastructure

The Rising Future of CPaaS in the Middle East 2024

The Rising Future of CPaaS in the Middle East 2024

What is Continuous Testing in DevOps - A Definitive Guide.pdf

What is Continuous Testing in DevOps - A Definitive Guide.pdf

Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...

Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...

美洲杯赔率投注网【网址🎉3977·EE🎉】

美洲杯赔率投注网【网址🎉3977·EE🎉】

Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx

Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx

Streamlining End-to-End Testing Automation

Streamlining End-to-End Testing Automation

- 1. CHEAT-SHEET Folding #4 ∶ / 𝒂𝟎 ∶ / 𝒂𝟏 ∶ / 𝒂𝟐 ∶ / 𝒂𝟑 𝒇 / 𝒂𝟎 𝒇 / 𝒂𝟏 𝒇 / 𝒂𝟐 𝒇 / 𝒂𝟑 𝒆 @philip_schwarz slides by https://fpilluminated.com/
- 2. We want to write function 𝒅𝒆𝒄𝒊𝒎𝒂𝒍, which given the digits of an integer number [𝑑0, 𝑑1, … , 𝑑𝑛] computes the integer value of the number - &'( ) 𝑑𝑘 ∗ 10)*& Thanks to the universal property of fold, if we are able to define 𝒅𝒆𝒄𝒊𝒎𝒂𝒍 so that its equations match those on the left hand side of the following equivalence, then we are also able to implement 𝒅𝒆𝒄𝒊𝒎𝒂𝒍 using a right fold i.e. given 𝑓𝑜𝑙𝑑𝑟 𝑓𝑜𝑙𝑑𝑟 :: 𝛼 → 𝛽 → 𝛽 → 𝛽 → 𝛼 → 𝛽 𝑓𝑜𝑙𝑑𝑟 𝑓 𝑣 = 𝑣 𝑓𝑜𝑙𝑑𝑟 𝑓 𝑣 𝑥 ∶ 𝑥𝑠 = 𝑓 𝑥 𝑓𝑜𝑙𝑑𝑟 𝑓 𝑣 𝑥𝑠 we can reimplement 𝒅𝒆𝒄𝒊𝒎𝒂𝒍 like this: 𝒅𝒆𝒄𝒊𝒎𝒂𝒍 = 𝑓𝑜𝑙𝑑𝑟 𝑓 𝑣 The universal property of 𝒇𝒐𝒍𝒅 𝒈 = 𝒗 ⟺ 𝒈 = 𝒇𝒐𝒍𝒅 𝒇 𝒗 𝒈 :: 𝛼 → 𝛽 𝒈 𝑥 ∶ 𝑥𝑠 = 𝒇 𝑥 𝒈 𝑥𝑠 𝒗 :: 𝛽 𝒇 :: 𝛼 → 𝛽 → 𝛽 scala> decimal(List(1,2,3,4)) val res0: Int = 1234 haskell> decimal [1,2,3,4] 1234 𝑑0 ∗ 103 + 𝑑1 ∗ 102 + 𝑑2 ∗ 101 + 𝑑3 ∗ 100 = 1 ∗ 1000 + 2 ∗ 100 + 3 ∗ 10 + 4 ∗ 1 = 1234
- 3. Notice that 𝒇 has two parameters: the head of the list, and the result of recursively calling 𝒈 with the tail of the list 𝒈 𝑥 ∶ 𝑥𝑠 = 𝒇 𝑥 𝒈 𝑥𝑠 In order to define our 𝒅𝒆𝒄𝒊𝒎𝒂𝒍 function however, the two parameters of 𝒇 are not sufficient. When 𝒅𝒆𝒄𝒊𝒎𝒂𝒍 is passed [𝑑𝑘, … , 𝑑𝑛], 𝒇 is passed digit 𝑑𝑘, so 𝒇 needs 𝑛 and 𝑘 in order to compute 10)*& , but 𝑛 − 𝑘 is the number of elements in [𝑑𝑘, … , 𝑑𝑛] minus one, so by nesting the definition of 𝒇 inside that of 𝒅𝒆𝒄𝒊𝒎𝒂𝒍, we can avoid explicitly adding a third parameter to 𝒇 : We nested 𝒇 inside 𝒅𝒆𝒄𝒊𝒎𝒂𝒍, so that the equations of 𝒅𝒆𝒄𝒊𝒎𝒂𝒍 match (almost) those of 𝒈. They don’t match perfectly, in that the 𝒇 nested inside 𝒅𝒆𝒄𝒊𝒎𝒂𝒍 depends on 𝒅𝒆𝒄𝒊𝒎𝒂𝒍’s list parameter, whereas the 𝒇 nested inside 𝒈 does not depend on 𝒈’s list parameter. Are we still able to redefine 𝒅𝒆𝒄𝒊𝒎𝒂𝒍 using 𝑓𝑜𝑙𝑑𝑟? If the match had been perfect, we would be able to define 𝒅𝒆𝒄𝒊𝒎𝒂𝒍 = 𝑓𝑜𝑙𝑑𝑟 𝑓 0 (with 𝒗 = 0), but because 𝒇 needs to know the value of 𝑛 − 𝑘, we can’t just pass 𝒇 to 𝑓𝑜𝑙𝑑𝑟, and use 0 as the initial accumulator. Instead, we need to use (0, 0) as the accumulator (the second 0 being the initial value of 𝑛 − 𝑘, when 𝑘 = 𝑛), and pass to 𝑓𝑜𝑙𝑑𝑟 a helper function ℎ that manages 𝑛 − 𝑘 and that wraps 𝒇, so that the latter has access to 𝑛 − 𝑘. def h(d: Int, acc: (Int,Int)): (Int,Int) = acc match { case (ds, e) => def f(d: Int, ds: Int): Int = d * Math.pow(10, e).toInt + ds (f(d, ds), e + 1) } def decimal(ds: List[Int]): Int = ds.foldRight((0,0))(h).head h :: Int -> (Int,Int) -> (Int,Int) h d (ds, e) = (f d ds, e + 1) where f :: Int -> Int -> Int f d ds = d * (10 ^ e) + ds decimal :: [Int] -> Int decimal ds = fst (foldr h (0,0) ds) def decimal(digits: List[Int]): Int = val e = digits.length-1 def f(d: Int, ds: Int): Int = d * Math.pow(10, e).toInt + ds digits match case Nil => 0 case d +: ds => f(d, decimal(ds)) decimal :: [Int] -> Int decimal [] = 0 decimal (d:ds) = f d (decimal ds) where e = length ds f :: Int -> Int -> Int f d ds = d * (10 ^ e) + ds The unnecessary complexity of the 𝒅𝒆𝒄𝒊𝒎𝒂𝒍 functions on this slide is purely due to them being defined in terms of 𝒇 . See next slide for simpler refactored versions in which 𝒇 is inlined.
- 4. def f(d: Int, acc: (Int,Int)): (Int,Int) = acc match case (ds, e) => (d * Math.pow(10, e).toInt + ds, e + 1) def decimal(ds: List[Int]): Int = ds.foldRight((0,0))(f).head f :: Int -> (Int,Int) -> (Int,Int) f d (ds, e) = (d * (10 ^ e) + ds, e + 1) decimal :: [Int] -> Int decimal ds = fst (foldr f (0,0) ds) def decimal(digits: List[Int]): Int = digits match case Nil => 0 case d +: ds => d * Math.pow(10, ds.length).toInt + decimal(ds) decimal :: [Int] -> Int decimal [] = 0 decimal (d:ds) = d*(10^(length ds))+(decimal ds) Same 𝒅𝒆𝒄𝒊𝒎𝒂𝒍 functions as on the previous slide, but refactored as follows: 1. inlined 𝒇 in all four functions 2. inlined e in the first two functions 3. renamed 𝒉 to 𝒇 in the last two functions
- 5. Not every function on lists can be defined as an instance of 𝑓𝑜𝑙𝑑𝑟. For example, zip cannot be so defined. Even for those that can, an alternative definition may be more efficient. To illustrate, suppose we want a function decimal that takes a list of digits and returns the corresponding decimal number; thus 𝑑𝑒𝑐𝑖𝑚𝑎𝑙 [𝑥0, 𝑥1, … , 𝑥n] = ∑!"# $ 𝑥𝑘10($&!) It is assumed that the most significant digit comes first in the list. One way to compute decimal efficiently is by a process of multiplying each digit by ten and adding in the following digit. For example 𝑑𝑒𝑐𝑖𝑚𝑎𝑙 𝑥0, 𝑥1, 𝑥2 = 10 × 10 × 10 × 0 + 𝑥0 + 𝑥1 + 𝑥2 This decomposition of a sum of powers is known as Horner’s rule. Suppose we define ⊕ by 𝑛 ⊕ 𝑥 = 10 × 𝑛 + 𝑥. Then we can rephrase the above equation as 𝑑𝑒𝑐𝑖𝑚𝑎𝑙 𝑥0, 𝑥1, 𝑥2 = (0 ⊕ 𝑥0) ⊕ 𝑥1 ⊕ 𝑥2 This is almost like an instance of 𝑓𝑜𝑙𝑑𝑟, except that the grouping is the other way round, and the starting value appears on the left, not on the right. In fact the computation is dual: instead of processing from right to left, the computation processes from left to right. This example motivates the introduction of a second fold operator called 𝑓𝑜𝑙𝑑𝑙 (pronounced ‘fold left’). Informally: 𝑓𝑜𝑙𝑑𝑙 ⊕ 𝑒 𝑥0, 𝑥1, … , 𝑥𝑛 − 1 = … ((𝑒 ⊕ 𝑥0) ⊕ 𝑥1) … ⊕ 𝑥𝑛 − 1 The parentheses group from the left, which is the reason for the name. The full definition of 𝑓𝑜𝑙𝑑𝑙 is 𝑓𝑜𝑙𝑑𝑙 ∷ 𝛽 → 𝛼 → 𝛽 → 𝛽 → 𝛼 → 𝛽 𝑓𝑜𝑙𝑑𝑙 𝑓 𝑒 = 𝑒 𝑓𝑜𝑙𝑑𝑙 𝑓 𝑒 𝑥: 𝑥𝑠 = 𝑓𝑜𝑙𝑑𝑙 𝑓 𝑓 𝑒 𝑥 𝑥𝑠 Richard Bird The definition of 𝒅𝒆𝒄𝒊𝒎𝒂𝒍 using a right fold is inefficient because it computes ∑!"# $ 𝑑𝑘 ∗ 10$&! by computing 10$&! for each 𝑘.
- 6. If we look back at our initial recursive definition of 𝒅𝒆𝒄𝒊𝒎𝒂𝒍, we see that it splits its list parameter into a head and a tail. If we get 𝒅𝒆𝒄𝒊𝒎𝒂𝒍 to split the list into init and last, we can make it more efficient by using Horner’s rule: We can then improve on that by going back to splitting the list into a head and a tail, and making 𝒅𝒆𝒄𝒊𝒎𝒂𝒍 tail recursive: And finally, we can improve on that by defining 𝒅𝒆𝒄𝒊𝒎𝒂𝒍 using a left fold: (⊕) :: Int -> Int -> Int n ⊕ d = 10 * n + d decimal :: [Int] -> Int decimal [] = 0 decimal (d:ds) = d*(10^(length ds)) + (decimal ds) def decimal(digits: List[Int]): Int = digits match case Nil => 0 case d +: ds => d * Math.pow(10, ds.length).toInt + decimal(ds) extension (n: Int) def ⊕(d Int): Int = 10 * n + d decimal :: [Int] -> Int -> Int decimal [] acc = acc decimal (d:ds) acc = decimal ds (acc ⊕d) def decimal(ds: List[Int], acc: Int=0): Int = digits match case Nil => acc case d +: ds => decimal(ds, acc ⊕ d) decimal :: [Int] -> Int decimal = foldl (⊕) 0 decimal :: [Int] -> Int decimal [] = 0 decimal ds = (decimal (init ds)) ⊕ (last ds) def decimal(digits: List[Int]): Int = digits match case Nil => 0 case ds :+ d => decimal(ds) ⊕ d def decimal(ds: List[Int]): Int = ds.foldLeft(0)(_⊕_)
- 7. Recap In the case of the 𝒅𝒆𝒄𝒊𝒎𝒂𝒍 function, defining it using a left fold is simple and mathematically more efficient whereas defining it using a right fold is more complex and mathematically less efficient def decimal(ds: List[Int]): Int = ds.foldRight((0,0))(f).head def f(d: Int, acc: (Int,Int)): (Int,Int) = acc match case (ds, e) => (d * Math.pow(10, e).toInt + ds, e + 1) decimal :: [Int] -> Int decimal ds = fst (foldr f (0,0) ds) f :: Int -> (Int,Int) -> (Int,Int) f d (ds, e) = (d * (10 ^ e) + ds, e + 1) decimal :: [Int] -> Int decimal = foldl (⊕) 0 (⊕) :: Int -> Int -> Int n ⊕ d = 10 * n + d def decimal(ds: List[Int]): Int = ds.foldLeft(0)(_⊕_) extension (n: Int) def ⊕(d Int): Int = 10 * n + d 𝒅𝒆𝒄𝒊𝒎𝒂𝒍 1,2,3,4 = 𝑑0 ∗ 103 + (𝑑1 ∗ 102 + (𝑑2 ∗ 101 + (𝑑3 ∗ 100 + 0))) = 1 ∗ 1000 + (2 ∗ 100 + (3 ∗ 10 + (4 ∗ 1 + 0))) = 1234 𝒅𝒆𝒄𝒊𝒎𝒂𝒍 1,2,3,4 = 10 ∗ 10 ∗ 10 ∗ 10 ∗ 0 + 𝑑0 + 𝑑1 + 𝑑2 + 𝑑3 = 10 ∗ (10 ∗ 10 ∗ 10 ∗ 0 + 1 + 2 + 3) + 4 = 1234