The document discusses functional programming concepts in Haskell compared to traditional imperative languages like C++. It provides:
1) An example of quicksort implemented in both C++ and Haskell to illustrate the differences in approach and syntax between the two paradigms. The Haskell version is much more concise, using only 5 lines compared to 14 lines in C++.
2) Explanations of key functional programming concepts in Haskell including pure functions, recursion, pattern matching, and higher-order functions like map and fold.
3) Examples and definitions of commonly used Haskell functions and data types to summarize lists, sorting, and traversing elements - highlighting the more declarative style of functional programming.
The document provides an overview of references and pointers in C++. References act as aliases for objects without copying them, while pointers store the address of an object and require dereferencing. References must be initialized and cannot be changed or null, whereas pointers can be null and changed. Const references and pointers promise not to modify an object.
In computer science, a linked list is a linear collection of data elements, whose order is not given by their physical placement in memory. Instead, each element points to the next. It is a data structure consisting of a collection of nodes which together represent a sequence.
This document discusses abstract data types (ADTs) and their implementation in various programming languages. It covers the key concepts of ADTs including data abstraction, encapsulation, information hiding, and defining the public interface separately from the private implementation. It provides examples of ADTs implemented using modules in Modula-2, packages in Ada, classes in C++, generics in Java and C#, and classes in Ruby. Parameterized and encapsulation constructs are also discussed as techniques for implementing and organizing ADTs.
The document discusses heap data structures and their use in priority queues and heapsort. It defines a heap as a complete binary tree stored in an array. Each node stores a value, with the heap property being that a node's value is greater than or equal to its children's values (for a max heap). Algorithms like Max-Heapify, Build-Max-Heap, Heap-Extract-Max, and Heap-Increase-Key are presented to maintain the heap property during operations. Priority queues use heaps to efficiently retrieve the maximum element, while heapsort sorts an array by building a max heap and repeatedly extracting elements.
The document discusses stacks and queues as linear data structures. It defines stacks and queues, describes their common operations like push, pop, insert and delete, and ways to implement them using arrays and linked lists. Array implementation of stacks and queues is shown along with diagrams. Linked list implementation of stacks and queues is also discussed with diagrams showing the insertion and deletion of nodes. Sample programs to implement stacks and queues using arrays and linked lists are mentioned.
The document discusses linear data structures and lists. It describes list abstract data types and their two main implementations: array-based and linked lists. It provides examples of singly linked lists, circular linked lists, and doubly linked lists. It also discusses applications of lists, including representing polynomials using lists.
A heap tree is a complete binary tree where each parent node has a value greater than or equal to its children. There are two types - max-heap and min-heap. A heap can be represented as an array where the root is at index 1 and children at 2i and 2i+1. Operations like insertion and deletion involve bubbling/sifting nodes up or down the tree to maintain the heap property. Heapsort uses a heap to sort an array by repeatedly extracting the max/min element.
The document provides an overview of references and pointers in C++. References act as aliases for objects without copying them, while pointers store the address of an object and require dereferencing. References must be initialized and cannot be changed or null, whereas pointers can be null and changed. Const references and pointers promise not to modify an object.
In computer science, a linked list is a linear collection of data elements, whose order is not given by their physical placement in memory. Instead, each element points to the next. It is a data structure consisting of a collection of nodes which together represent a sequence.
This document discusses abstract data types (ADTs) and their implementation in various programming languages. It covers the key concepts of ADTs including data abstraction, encapsulation, information hiding, and defining the public interface separately from the private implementation. It provides examples of ADTs implemented using modules in Modula-2, packages in Ada, classes in C++, generics in Java and C#, and classes in Ruby. Parameterized and encapsulation constructs are also discussed as techniques for implementing and organizing ADTs.
The document discusses heap data structures and their use in priority queues and heapsort. It defines a heap as a complete binary tree stored in an array. Each node stores a value, with the heap property being that a node's value is greater than or equal to its children's values (for a max heap). Algorithms like Max-Heapify, Build-Max-Heap, Heap-Extract-Max, and Heap-Increase-Key are presented to maintain the heap property during operations. Priority queues use heaps to efficiently retrieve the maximum element, while heapsort sorts an array by building a max heap and repeatedly extracting elements.
The document discusses stacks and queues as linear data structures. It defines stacks and queues, describes their common operations like push, pop, insert and delete, and ways to implement them using arrays and linked lists. Array implementation of stacks and queues is shown along with diagrams. Linked list implementation of stacks and queues is also discussed with diagrams showing the insertion and deletion of nodes. Sample programs to implement stacks and queues using arrays and linked lists are mentioned.
The document discusses linear data structures and lists. It describes list abstract data types and their two main implementations: array-based and linked lists. It provides examples of singly linked lists, circular linked lists, and doubly linked lists. It also discusses applications of lists, including representing polynomials using lists.
A heap tree is a complete binary tree where each parent node has a value greater than or equal to its children. There are two types - max-heap and min-heap. A heap can be represented as an array where the root is at index 1 and children at 2i and 2i+1. Operations like insertion and deletion involve bubbling/sifting nodes up or down the tree to maintain the heap property. Heapsort uses a heap to sort an array by repeatedly extracting the max/min element.
This document discusses various sorting algorithms and their complexities. It begins by defining an algorithm and complexity measures like time and space complexity. It then defines sorting and common sorting algorithms like bubble sort, selection sort, insertion sort, quicksort, and mergesort. For each algorithm, it provides a high-level overview of the approach and time complexity. It also covers sorting algorithm concepts like stable and unstable sorting. The document concludes by discussing future directions for sorting algorithms and their applications.
This document summarizes different types of operators in Java including assignment, increment/decrement, arithmetic, bitwise, relational, logical, ternary, shift, and instance of operators. It provides examples of each type of operator and describes what they are used for such as assigning values, performing mathematical operations, comparing values, and checking object types. The key types of operators covered are assignment, arithmetic, relational, logical, and instance of operators.
The document discusses Java Sets and Maps. It describes that a Set is an unordered collection with no duplicates, while a Map maps keys to values with no duplicate keys. Common Set implementations are HashSet, TreeSet, and LinkedHashSet. Common Map implementations are HashMap and TreeMap. The document provides examples of typical operations on Sets like contains, add, remove, and iterating with iterators or enhanced for loops. It also discusses operations on Maps like put, get, remove, and iterating over the keySet, values, or entrySet.
String objects are immutable in Java, so any operation that modifies a String value actually creates a new String object. The StringBuffer and StringBuilder classes provide mutable alternatives to String that have similar methods but do not create new objects with each modification. When a String literal value is used in code, it is stored in the String constant pool to promote reuse of these immutable objects.
Object oriented programming with pythonArslan Arshad
A short intro to how Object Oriented Paradigm work in Python Programming language. This presentation created for beginner like bachelor student of Computer Science.
This document discusses various Python functions concepts including defining simple functions, functions with arguments, default arguments, lambda functions, generators, and decorators. It provides examples of defining functions that take positional and keyword arguments, using lambda functions, creating generators using yield, and applying decorators to functions. Various introspection methods like type(), dir(), and callable() are also covered.
Asynchronous programming is a method of programming that can allow multiple different things to be run concurrently (or in parallel). In Rust, it is accomplished using a high-level idea called a Future.
Asynchronous programming is used a lot for IO because there are many times where you have to wait for something to happen (such as reading from a socket or a file) during which no progress can be made. This is a perfect moment to hand over control to something else so that it can start to make progress. This allows our program to always be making progress, which is the name of the game.
Go through this slides, where Pawan Bisht will be talking about the asynchronous concept in Rust Programming like what operations performed by the Rust compiler that actually makes our code asynchronous and what's the role of waker, poll, etc. With this, you can increase your software/application's performance and responsiveness.
This document outlines PHP functions including function declaration, arguments, returning values, variable scope, static variables, recursion, and useful built-in functions. Functions are blocks of code that perform tasks and can take arguments. They are declared with the function keyword followed by the name and parameters. Functions can return values and arguments are passed by value by default but can also be passed by reference. Variable scope inside functions refers to the local scope unless specified as global. Static variables retain their value between function calls. Recursion occurs when a function calls itself. Useful built-in functions include function_exists() and get_defined_functions().
This document provides an overview of pointers in C++. It defines pointers as variables that store the memory address of another variable. It discusses declaring and initializing pointer variables, pointer operators like & and *, pointer arithmetic, passing pointers to functions, arrays of pointers, strings of pointers, objects of pointers, and the this pointer. Advantages of pointers include efficient handling of arrays, direct memory access for speed, reduced storage space, and support for complex data structures. Limitations include slower performance than normal variables, inability to store values, needing null references, and risk of errors from incorrect initialization.
C language is a structured, procedural programming language developed in the early 1970s by Dennis Ritchie at Bell Labs. Some key points:
- C was created to develop the UNIX operating system and is still widely used for systems programming.
- Major features were derived from an earlier language called B.
- It is a middle-level language that provides low-level access to memory and hardware.
- C has been widely adopted and is one of the most popular and widely used languages, forming the basis for many other popular languages like C++ and Java. Areas where C is commonly used include operating systems, graphics applications, and compilers.
This document discusses implementing stacks and queues using linked lists. For a stack, elements are inserted and removed from the head (start) of the linked list for constant time operations. For a queue, elements are inserted at the head and removed from the tail (end) of the linked list, requiring traversing to the second last node for removal. Implementing stacks and queues with linked lists avoids size limitations of arrays and uses dynamic memory allocation.
Video and slides synchronized, mp3 and slide download available at URL http://bit.ly/28XnVtb.
Felix Klock describe the core concepts of the Rust language (ownership, borrowing, and lifetimes), as well as the tools beyond the compiler for open source software component distribution (cargo, crates.io). Filmed at qconlondon.com.
Felix Klock is a research engineer at Mozilla, where he works on the Rust compiler, runtime libraries, and language design. He previously worked on the ActionScript Virtual Machine for the Adobe Flash runtime. Klock is one of the developers of the Larceny Scheme language runtime.
The document discusses Strings in Java. Some key points:
- A String represents a sequence of characters. The String class is used to create string objects which can exist in the string pool or heap.
- Char arrays are preferable over Strings for passwords due to security reasons. Strings can be manipulated more easily.
- The String class has many useful methods like length(), charAt(), indexOf(), replace(), toLowerCase(), substring() etc to work with and manipulate string values.
- StringBuffer is used to create mutable string objects that can be modified after creation using methods like append(), insert(), delete() etc. It is preferable over String for performance reasons while manipulating strings.
This document discusses Java packages and interfaces. It covers topics like:
- Packages are used to group related classes and interfaces and provide benefits like reuse and separation of design from code.
- Well-known Java API packages include java.lang, java.util, java.io, java.awt, and java.net.
- There are two ways to access classes from packages: using fully qualified names or import statements.
- Interfaces are used for multiple inheritance in Java and define abstract methods that implementing classes must define. Interfaces can extend other interfaces.
Quicksort is a divide and conquer algorithm that works by partitioning an array around a pivot value and recursively sorting the sub-partitions. It first chooses a pivot element and partitions the array by placing all elements less than the pivot before it and all elements greater than it after it. It then recursively quicksorts the two partitions. This continues until the individual partitions only contain single elements at which point they are sorted. Quicksort has average case performance of O(n log n) time making it very efficient for large data sets.
The document discusses stacks and their implementation. It introduces stacks and their common operations like push and pop. It describes using stacks to solve problems like reversing a list, calculating in Reverse Polish Notation, and bracket matching by keeping track of opening brackets on a stack. Sample code is provided to implement a stack class with methods like push, pop and top to manipulate items on the stack.
The document discusses binary expression trees, which are a type of binary tree used to represent arithmetic expressions. A binary expression tree has operands as leaf nodes and operators as internal nodes. The left and right subtrees of each operator node represent subexpressions that must be evaluated before applying the operator. The document provides examples of binary expression trees and discusses traversing them using inorder, preorder, and postorder traversals. Algorithms are presented for building a binary expression tree from a prefix notation expression and for evaluating an expression by scanning it and using operator and value stacks.
The document provides an overview of fundamental JavaScript concepts such as variables, data types, operators, control structures, functions, and objects. It also covers DOM manipulation and interacting with HTML elements. Code examples are provided to demonstrate JavaScript syntax and how to define and call functions, work with arrays and objects, and select and modify elements of a web page.
This document discusses monads and parsers in Haskell. It introduces monads and defines monads for basic evaluation, exception handling, and state handling. It then defines a monadic parser and shows how to build parsers using monad combinators. Finally, it discusses zippers for structured data like trees and lists, allowing navigation and local updates.
AdRoll Tech Talk Presentation:
In this talk I present three approaches to understanding monads:
- How Monads Arise Naturally
- Monads as Implemented in Haskell
- Monads in Category Theory
This document discusses various sorting algorithms and their complexities. It begins by defining an algorithm and complexity measures like time and space complexity. It then defines sorting and common sorting algorithms like bubble sort, selection sort, insertion sort, quicksort, and mergesort. For each algorithm, it provides a high-level overview of the approach and time complexity. It also covers sorting algorithm concepts like stable and unstable sorting. The document concludes by discussing future directions for sorting algorithms and their applications.
This document summarizes different types of operators in Java including assignment, increment/decrement, arithmetic, bitwise, relational, logical, ternary, shift, and instance of operators. It provides examples of each type of operator and describes what they are used for such as assigning values, performing mathematical operations, comparing values, and checking object types. The key types of operators covered are assignment, arithmetic, relational, logical, and instance of operators.
The document discusses Java Sets and Maps. It describes that a Set is an unordered collection with no duplicates, while a Map maps keys to values with no duplicate keys. Common Set implementations are HashSet, TreeSet, and LinkedHashSet. Common Map implementations are HashMap and TreeMap. The document provides examples of typical operations on Sets like contains, add, remove, and iterating with iterators or enhanced for loops. It also discusses operations on Maps like put, get, remove, and iterating over the keySet, values, or entrySet.
String objects are immutable in Java, so any operation that modifies a String value actually creates a new String object. The StringBuffer and StringBuilder classes provide mutable alternatives to String that have similar methods but do not create new objects with each modification. When a String literal value is used in code, it is stored in the String constant pool to promote reuse of these immutable objects.
Object oriented programming with pythonArslan Arshad
A short intro to how Object Oriented Paradigm work in Python Programming language. This presentation created for beginner like bachelor student of Computer Science.
This document discusses various Python functions concepts including defining simple functions, functions with arguments, default arguments, lambda functions, generators, and decorators. It provides examples of defining functions that take positional and keyword arguments, using lambda functions, creating generators using yield, and applying decorators to functions. Various introspection methods like type(), dir(), and callable() are also covered.
Asynchronous programming is a method of programming that can allow multiple different things to be run concurrently (or in parallel). In Rust, it is accomplished using a high-level idea called a Future.
Asynchronous programming is used a lot for IO because there are many times where you have to wait for something to happen (such as reading from a socket or a file) during which no progress can be made. This is a perfect moment to hand over control to something else so that it can start to make progress. This allows our program to always be making progress, which is the name of the game.
Go through this slides, where Pawan Bisht will be talking about the asynchronous concept in Rust Programming like what operations performed by the Rust compiler that actually makes our code asynchronous and what's the role of waker, poll, etc. With this, you can increase your software/application's performance and responsiveness.
This document outlines PHP functions including function declaration, arguments, returning values, variable scope, static variables, recursion, and useful built-in functions. Functions are blocks of code that perform tasks and can take arguments. They are declared with the function keyword followed by the name and parameters. Functions can return values and arguments are passed by value by default but can also be passed by reference. Variable scope inside functions refers to the local scope unless specified as global. Static variables retain their value between function calls. Recursion occurs when a function calls itself. Useful built-in functions include function_exists() and get_defined_functions().
This document provides an overview of pointers in C++. It defines pointers as variables that store the memory address of another variable. It discusses declaring and initializing pointer variables, pointer operators like & and *, pointer arithmetic, passing pointers to functions, arrays of pointers, strings of pointers, objects of pointers, and the this pointer. Advantages of pointers include efficient handling of arrays, direct memory access for speed, reduced storage space, and support for complex data structures. Limitations include slower performance than normal variables, inability to store values, needing null references, and risk of errors from incorrect initialization.
C language is a structured, procedural programming language developed in the early 1970s by Dennis Ritchie at Bell Labs. Some key points:
- C was created to develop the UNIX operating system and is still widely used for systems programming.
- Major features were derived from an earlier language called B.
- It is a middle-level language that provides low-level access to memory and hardware.
- C has been widely adopted and is one of the most popular and widely used languages, forming the basis for many other popular languages like C++ and Java. Areas where C is commonly used include operating systems, graphics applications, and compilers.
This document discusses implementing stacks and queues using linked lists. For a stack, elements are inserted and removed from the head (start) of the linked list for constant time operations. For a queue, elements are inserted at the head and removed from the tail (end) of the linked list, requiring traversing to the second last node for removal. Implementing stacks and queues with linked lists avoids size limitations of arrays and uses dynamic memory allocation.
Video and slides synchronized, mp3 and slide download available at URL http://bit.ly/28XnVtb.
Felix Klock describe the core concepts of the Rust language (ownership, borrowing, and lifetimes), as well as the tools beyond the compiler for open source software component distribution (cargo, crates.io). Filmed at qconlondon.com.
Felix Klock is a research engineer at Mozilla, where he works on the Rust compiler, runtime libraries, and language design. He previously worked on the ActionScript Virtual Machine for the Adobe Flash runtime. Klock is one of the developers of the Larceny Scheme language runtime.
The document discusses Strings in Java. Some key points:
- A String represents a sequence of characters. The String class is used to create string objects which can exist in the string pool or heap.
- Char arrays are preferable over Strings for passwords due to security reasons. Strings can be manipulated more easily.
- The String class has many useful methods like length(), charAt(), indexOf(), replace(), toLowerCase(), substring() etc to work with and manipulate string values.
- StringBuffer is used to create mutable string objects that can be modified after creation using methods like append(), insert(), delete() etc. It is preferable over String for performance reasons while manipulating strings.
This document discusses Java packages and interfaces. It covers topics like:
- Packages are used to group related classes and interfaces and provide benefits like reuse and separation of design from code.
- Well-known Java API packages include java.lang, java.util, java.io, java.awt, and java.net.
- There are two ways to access classes from packages: using fully qualified names or import statements.
- Interfaces are used for multiple inheritance in Java and define abstract methods that implementing classes must define. Interfaces can extend other interfaces.
Quicksort is a divide and conquer algorithm that works by partitioning an array around a pivot value and recursively sorting the sub-partitions. It first chooses a pivot element and partitions the array by placing all elements less than the pivot before it and all elements greater than it after it. It then recursively quicksorts the two partitions. This continues until the individual partitions only contain single elements at which point they are sorted. Quicksort has average case performance of O(n log n) time making it very efficient for large data sets.
The document discusses stacks and their implementation. It introduces stacks and their common operations like push and pop. It describes using stacks to solve problems like reversing a list, calculating in Reverse Polish Notation, and bracket matching by keeping track of opening brackets on a stack. Sample code is provided to implement a stack class with methods like push, pop and top to manipulate items on the stack.
The document discusses binary expression trees, which are a type of binary tree used to represent arithmetic expressions. A binary expression tree has operands as leaf nodes and operators as internal nodes. The left and right subtrees of each operator node represent subexpressions that must be evaluated before applying the operator. The document provides examples of binary expression trees and discusses traversing them using inorder, preorder, and postorder traversals. Algorithms are presented for building a binary expression tree from a prefix notation expression and for evaluating an expression by scanning it and using operator and value stacks.
The document provides an overview of fundamental JavaScript concepts such as variables, data types, operators, control structures, functions, and objects. It also covers DOM manipulation and interacting with HTML elements. Code examples are provided to demonstrate JavaScript syntax and how to define and call functions, work with arrays and objects, and select and modify elements of a web page.
This document discusses monads and parsers in Haskell. It introduces monads and defines monads for basic evaluation, exception handling, and state handling. It then defines a monadic parser and shows how to build parsers using monad combinators. Finally, it discusses zippers for structured data like trees and lists, allowing navigation and local updates.
AdRoll Tech Talk Presentation:
In this talk I present three approaches to understanding monads:
- How Monads Arise Naturally
- Monads as Implemented in Haskell
- Monads in Category Theory
El documento describe las principales organizaciones e iniciativas internacionales relacionadas con el cambio climático. El IPCC evalúa la ciencia del cambio climático y recibió el Premio Nobel de la Paz en 2007. La Convención Marco de las Naciones Unidas sobre el Cambio Climático de 1992 estableció un marco para reducir las emisiones de gases de efecto invernadero. El Protocolo de Kioto de 1997 contiene medidas más estrictas. La COP supervisa la aplicación de la Convención y el Protocolo a través de reuniones anual
Este documento es un PowerPoint que invita al usuario a enviarlo a un amigo o suscribirse para recibir más presentaciones gratis por correo electrónico. Ofrece enlaces para compartir el archivo o registrarse para futuras presentaciones.
Presentation on Functional Programming in a for-profit company using OCaml, presented on December 14th 2011 at Ghent University (UGent).
Due to the Haskell background of the attendees, OCaml was introduced with this in mind.
A short talk on what makes Functional Programming - and especially Haskell - different.
We'll take a quick overview of Haskell's features and coding style, and then work through a short but complete example of using it for a Real World problem.
http://lanyrd.com/2011/geekup-liverpool-may/sdykh/
This document summarizes a presentation on teaching Haskell without requiring an understanding of monads. It argues that emphasizing monads early on causes unnecessary confusion and frustration for beginners. Historically, Haskell was designed to be practical and used in applications, not just academia. However, referring to I/O as the "IO monad" has been hugely misleading and harmful to newcomers, as it leads them to obsess over understanding monads before they are ready. In reality, Haskell's I/O can be easily used without knowing anything about monads.
This document provides an overview of functional programming with Haskell. It discusses key concepts of functional programming like immutable data structures and pure functions. It introduces Haskell types including basic types, tuples, lists, data types, and type classes. It covers Haskell functions like pattern matching, guards, and higher order functions. It also discusses Haskell concepts like laziness, currying, and polymorphism. Finally, it provides an introduction to monads in Haskell and discusses Haskell tools, frameworks, and performance.
Introducing Monads and State Monad at PSUGDavid Galichet
This document discusses using the State monad to model a game where two robots move on a playground according to instructions, gathering coins. It first introduces functors, monads and for comprehensions in Scala. It then models the game state as a playground containing robots with positions and scores. The robots evolve by processing instructions in a state monad, allowing functional, pure modeling of state changes. Processing all instructions results in a state monad that can be run with the initial playground state.
This document summarizes Lecture 1 of Real World Haskell. It introduces functional programming and Haskell, discusses the Haskell Platform and interactive interpreter ghci. It demonstrates defining simple functions and expressions, writing small interactive programs, and using recursion to number lines of text. Resources for learning more about Haskell are provided.
The document describes using the State monad to model a simulation of two robots moving on a playground and gathering coins in a purely functional way. Key points:
- The simulation involves modeling state as robots move through positions on a playground and scores are updated
- Types like Position, Robot, Playground are defined to represent the game state
- The State monad is introduced to abstract over state manipulations in a functional way
- Methods like processInstruction are used to update the state after each robot move or turn
- compileInstructions uses the State monad and recursion to process the robot instructions lists while chaining the state updates
Modern SQL in Open Source and Commercial DatabasesMarkus Winand
SQL has gone out of fashion lately—partly due to the NoSQL movement, but mostly because SQL is often still used like 20 years ago. As a matter of fact, the SQL standard continued to evolve during the past decades resulting in the current release of 2016. In this session, we will go through the most important additions since the widely known SQL-92. We will cover common table expressions and window functions in detail and have a very short look at the temporal features of SQL:2011 and row pattern matching from SQL:2016.
Links:
http://modern-sql.com/
http://winand.at/
http://sql-performance-explained.com/
This document discusses basic loops and functions in R programming. It covers control statements like loops and if/else, arithmetic and boolean operators, default argument values, and returning values from functions. It also describes R programming structures, recursion, and provides an example of implementing quicksort recursively and constructing a binary search tree. The key topics are loops, control flow, functions, recursion, and examples of sorting and binary trees.
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.
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
Function Programming in Scala.
A lot of my examples here comes from the book
Functional programming in Scala By Paul Chiusano and Rúnar Bjarnason, It is a good book, buy it.
The document provides information about functional programming languages and concepts including:
1) Haskell and ML are introduced as functional languages with features like strong typing, algebraic data types, and pattern matching.
2) Core functional programming concepts are explained like referential transparency, higher-order functions, and recursion instead of iteration.
3) Fold functions are summarized as a way to iterate over lists in functional languages in both a left and right oriented way.
This document discusses first-class functions and lambda calculus. It begins with an overview of Alonzo Church and the origins of lambda calculus. It then covers first-class functions in JavaScript, functions as objects in Java, and first-class functions in Scala. The document also discusses generic higher-order functions and control abstraction.
The document discusses Python's built-in functions for functional programming: map(), filter(), reduce(), and lambda. It provides examples of using each function to transform sequences. Map applies a function to each item in a sequence. Filter filters items based on a function that tests each item. Reduce combines items via a function to produce a single value. These functions allow functional-style programming in Python.
Humble introduction to category theory in haskellJongsoo Lee
This document introduces category theory concepts in Haskell including functors, applicative functors, and monads. It provides examples of these concepts in Haskell like Maybe and lists being instances of functor and applicative. Functors allow mapping a function over a data type using fmap. Applicative functors allow chaining functions using pure and <*>. Monads generalize applicative functors and allow sequencing computations. The document recommends understanding these concepts as patterns found in Haskell code rather than focusing on their category theory origins.
Haskell is a pure functional programming language that was created in 1987 by a committee of researchers. It features lazy evaluation, pattern matching, list comprehensions, and type polymorphism. Haskell does not use variables or loops, instead relying on recursion. It has evolved over time from Haskell 1.0 to the current Haskell 2010 standard. For beginners, Hugs is a good starting point, while Haskell Platform is recommended for developers.
The document discusses functional programming and pattern matching. It provides examples of using pattern matching in functional programming to:
1. Match on algebraic data types like lists to traverse and operate on data in a recursive manner. Pattern matching allows adding new operations easily by adding new patterns.
2. Use pattern matching in variable declarations to destructure data like tuples and case class objects.
3. Perform pattern matching on function parameters to selectively apply different logic based on the patterns, like filtering even numbers from a list. Everything can be treated as values and expressions in functional programming.
R is an open source programming language for statistical analysis and graphics. It is widely used among statisticians and data miners. The document provides an introduction to R and examples of basic commands like getting the directory, assigning values, calculating mean and variance, linear modeling, and graphical representation. It also demonstrates logical implementations like conditionals, ifelse statements, for loops, while loops, and apply functions to iterate over vectors and lists.
This document discusses recursion in Haskell. It notes that unlike imperative languages, computations in Haskell are done by declaring what something is rather than how to get it. It then provides examples of translating imperative functions like factorial and finding the maximum value in a list to recursive functions in Haskell. It also discusses features like lambda functions, folding, scanning, and the differences between foldl and foldr. Throughout it emphasizes defining functions recursively based on simple base cases and recursive calls.
This document provides an overview of MATLAB, including:
- MATLAB is a program for numerical computation originally designed for linear algebra problems using matrices. It has since expanded to other types of scientific computations and graphics.
- The main components of the MATLAB interface are the command window, workspace, history, and editor. Help is accessed using commands like help, doc, and demo.
- MATLAB treats all variables as matrices and supports operations on matrices and vectors. Basic math, logical, and relational operators are covered.
- The document discusses plotting, flow control using if/else, switch/case and loops, writing M-files including functions, and saving and loading workspace and data files.
This document provides an overview of MATLAB, including:
- MATLAB is a program for numerical computation originally designed for linear algebra problems using matrices. It has since expanded to other types of scientific computations and graphics.
- The main components of the MATLAB interface are the command window, workspace, history, and editor. Help is accessed using commands like help, doc, and demo.
- MATLAB treats all variables as matrices and supports vectors, scalars, and relational, logical, and math operators on matrices. Functions include trigonometric, exponential, logical, and matrix functions.
- Plots can be generated by passing vectors to plot, and annotated using commands like title, xlabel, ylabel, and legend. Flow control includes if/
This document provides an overview of MATLAB, including:
- MATLAB is a program for numerical computation originally designed for linear algebra problems using matrices. It has since expanded to other types of scientific computations and graphics.
- The main components of the MATLAB interface are the command window, workspace, history, and editor. Help is accessed using commands like help, doc, and demo.
- MATLAB treats all variables as matrices and supports operations on matrices and vectors. Basic math, logical, and relational operators are supported.
- Functions include trigonometric, exponential, logical, matrix creation and manipulation, and plotting functions. Flow control includes if/else statements and for/while loops.
- M-files can contain scripts of
This document provides an overview of MATLAB, including:
- MATLAB is a program for numerical computation originally designed for linear algebra problems using matrices. It has since expanded to other types of scientific computations and graphics.
- The main components of the MATLAB interface are the command window, workspace, history, and editor. Help is accessed using commands like help, doc, and demo.
- MATLAB treats all variables as matrices and supports operations on matrices and vectors. Basic math, logical, and relational operators are covered.
- The document discusses plotting, flow control using if/else, switch/case and loops, writing M-files including functions, and saving and loading workspace and data files.
This document provides an overview of MATLAB, including:
- MATLAB is a program for numerical computation originally designed for linear algebra problems using matrices. It has since expanded to other types of scientific computations and graphics.
- The main components of the MATLAB interface are the command window, workspace, history, and editor. Help is accessed using commands like help, doc, and demo.
- MATLAB treats all variables as matrices and supports vectors, scalars, and relational, logical, and math operators on matrices. Functions include trigonometric, exponential, logical, and matrix functions.
- Plots can be generated by passing vectors to plot, and annotated using commands like title, xlabel, ylabel, and legend. Flow control includes if/
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.
The Functional Programming Triad of Folding, Scanning and Iteration - a first...Philip Schwarz
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
Similar to Functional Programming by Examples using Haskell (20)
Walmart Business+ and Spark Good for Nonprofits.pdfTechSoup
"Learn about all the ways Walmart supports nonprofit organizations.
You will hear from Liz Willett, the Head of Nonprofits, and hear about what Walmart is doing to help nonprofits, including Walmart Business and Spark Good. Walmart Business+ is a new offer for nonprofits that offers discounts and also streamlines nonprofits order and expense tracking, saving time and money.
The webinar may also give some examples on how nonprofits can best leverage Walmart Business+.
The event will cover the following::
Walmart Business + (https://business.walmart.com/plus) is a new shopping experience for nonprofits, schools, and local business customers that connects an exclusive online shopping experience to stores. Benefits include free delivery and shipping, a 'Spend Analytics” feature, special discounts, deals and tax-exempt shopping.
Special TechSoup offer for a free 180 days membership, and up to $150 in discounts on eligible orders.
Spark Good (walmart.com/sparkgood) is a charitable platform that enables nonprofits to receive donations directly from customers and associates.
Answers about how you can do more with Walmart!"
How to Manage Your Lost Opportunities in Odoo 17 CRMCeline George
Odoo 17 CRM allows us to track why we lose sales opportunities with "Lost Reasons." This helps analyze our sales process and identify areas for improvement. Here's how to configure lost reasons in Odoo 17 CRM
A review of the growth of the Israel Genealogy Research Association Database Collection for the last 12 months. Our collection is now passed the 3 million mark and still growing. See which archives have contributed the most. See the different types of records we have, and which years have had records added. You can also see what we have for the future.
The simplified electron and muon model, Oscillating Spacetime: The Foundation...RitikBhardwaj56
Discover the Simplified Electron and Muon Model: A New Wave-Based Approach to Understanding Particles delves into a groundbreaking theory that presents electrons and muons as rotating soliton waves within oscillating spacetime. Geared towards students, researchers, and science buffs, this book breaks down complex ideas into simple explanations. It covers topics such as electron waves, temporal dynamics, and the implications of this model on particle physics. With clear illustrations and easy-to-follow explanations, readers will gain a new outlook on the universe's fundamental nature.
A workshop hosted by the South African Journal of Science aimed at postgraduate students and early career researchers with little or no experience in writing and publishing journal articles.
Executive Directors Chat Leveraging AI for Diversity, Equity, and InclusionTechSoup
Let’s explore the intersection of technology and equity in the final session of our DEI series. Discover how AI tools, like ChatGPT, can be used to support and enhance your nonprofit's DEI initiatives. Participants will gain insights into practical AI applications and get tips for leveraging technology to advance their DEI goals.
Main Java[All of the Base Concepts}.docxadhitya5119
This is part 1 of my Java Learning Journey. This Contains Custom methods, classes, constructors, packages, multithreading , try- catch block, finally block and more.
This presentation includes basic of PCOS their pathology and treatment and also Ayurveda correlation of PCOS and Ayurvedic line of treatment mentioned in classics.
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPRAHUL
This Dissertation explores the particular circumstances of Mirzapur, a region located in the
core of India. Mirzapur, with its varied terrains and abundant biodiversity, offers an optimal
environment for investigating the changes in vegetation cover dynamics. Our study utilizes
advanced technologies such as GIS (Geographic Information Systems) and Remote sensing to
analyze the transformations that have taken place over the course of a decade.
The complex relationship between human activities and the environment has been the focus
of extensive research and worry. As the global community grapples with swift urbanization,
population expansion, and economic progress, the effects on natural ecosystems are becoming
more evident. A crucial element of this impact is the alteration of vegetation cover, which plays a
significant role in maintaining the ecological equilibrium of our planet.Land serves as the foundation for all human activities and provides the necessary materials for
these activities. As the most crucial natural resource, its utilization by humans results in different
'Land uses,' which are determined by both human activities and the physical characteristics of the
land.
The utilization of land is impacted by human needs and environmental factors. In countries
like India, rapid population growth and the emphasis on extensive resource exploitation can lead
to significant land degradation, adversely affecting the region's land cover.
Therefore, human intervention has significantly influenced land use patterns over many
centuries, evolving its structure over time and space. In the present era, these changes have
accelerated due to factors such as agriculture and urbanization. Information regarding land use and
cover is essential for various planning and management tasks related to the Earth's surface,
providing crucial environmental data for scientific, resource management, policy purposes, and
diverse human activities.
Accurate understanding of land use and cover is imperative for the development planning
of any area. Consequently, a wide range of professionals, including earth system scientists, land
and water managers, and urban planners, are interested in obtaining data on land use and cover
changes, conversion trends, and other related patterns. The spatial dimensions of land use and
cover support policymakers and scientists in making well-informed decisions, as alterations in
these patterns indicate shifts in economic and social conditions. Monitoring such changes with the
help of Advanced technologies like Remote Sensing and Geographic Information Systems is
crucial for coordinated efforts across different administrative levels. Advanced technologies like
Remote Sensing and Geographic Information Systems
9
Changes in vegetation cover refer to variations in the distribution, composition, and overall
structure of plant communities across different temporal and spatial scales. These changes can
occur natural.
Strategies for Effective Upskilling is a presentation by Chinwendu Peace in a Your Skill Boost Masterclass organisation by the Excellence Foundation for South Sudan on 08th and 09th June 2024 from 1 PM to 3 PM on each day.
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Dr. Vinod Kumar Kanvaria
Exploiting Artificial Intelligence for Empowering Researchers and Faculty,
International FDP on Fundamentals of Research in Social Sciences
at Integral University, Lucknow, 06.06.2024
By Dr. Vinod Kumar Kanvaria
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Functional Programming by Examples using Haskell
1. Functional Programming by Examples
A Little Taste of Haskell
Ihar I Hancharenka
EPAM Systems
July-Sept, 2011
2. Traditional programming languages
In traditional (imperative) programming languages (like C, C++,
Java, ...):
x = x + 1;
what is x mathematically ? it is not a (constant) function !
fundamental notion: state Γ ∈ {variables} → N ∪ R ∪ ...
every statement is a transformation of environmennts Γ → Γ )
This makes it difficult to reason about a program, i.e. prove its
correctness.
3. Functional programming languages
In a pure functional programming language (Haskell), every
function is also a function in the mathematical sense:
no pointers (and UGLY CrashDump, ACCESS VIOLATION,
NullPointerException and so on...)
no variables - but constant function (sometimes, imperative
PL variables are convertedd to SSA form at compilation
phase)
no loops - recursion as a magic bullet
We can prove properties of programs by the usual mathematical
means! (induction, case analysis)
Partial functions are allowed !
4. The Quicksort algorithm has been invented by SIR C.A.R. Hoare.
At that time - just a Tony Hoare.
5. Here’s a typical C++ implementation:
Example
1 void quickSort(int arr[], int left, int right)
2 {
3 int i = left, j = right;
4 int pivot = arr[(left + right) / 2];
5 while (i <= j)
6 {
7 while (arr[i] < pivot) ++i;
8 while (arr[j] > pivot) ++j;
9 if (i <= j)
10 std::swap(arr[i++], arr[j--]);
11 }
12 if (left < j) quickSort(arr, left, j);
13 if (i < right) quickSort(arr, i, right);
14 }
9. Now let’s describe the Haskell implementation of quicksort.
But first let’s see the result of using quicksort at some sample
input data.
Example
> qsort [2,5,3,2,1]
[1,2,2,3,5]
The numbers in square brackets [] is a regular haskell list (of
numbers).
But we can sort list of Char-s, Float-s and other types also.
10. But what is a List from Haskell point of view?
Definition
data [a] = [] | a:[a]
This is an example of recursively-defined data structure (has no
analogs in C++).
Here we define a base case - [] for an empty list and a recursive
one - item (:) list. And here’s some examples with syntactic sugar:
Example
[1..3] == [1,2,3] == 1:[2,3] == 1:2:3:[]
But the Haskell itself always treats is like a degenerated tree
(1:(2:(3:[])))
11. Now it’s time to look at the first line of our quicksort:
Definition
qsort :: Ord a => [a] -> [a]
This is just a type declaration of qsort function.
a
is a type variable (can be Integer, Float, Char, ...).
Ord a =>
is a constraint for the type a (it shold support total ordering).
[a] -> [a]
means that qsort takes a list of some time and return the
[sorted] list of the same type.
12. It worth to be mentioned:
FYI
It’s not needed to put type declaration for all the functions.
In most cases it will be automatically deduced.
According to the Hindley-Milner type inference algorithm.
13. Let’s look at the Ord type class (corresponds to something like
interface in Java/C/C++):
Definition
data Ordering = LT | EQ | GT
-- Minimal complete definition: either ’compare’ or ’<=’.
-- Using ’compare’ can be more efficient for complex types.
--
class (Eq a) => Ord a where
compare :: a -> a -> Ordering
(<), (<=), (>), (>=) :: a -> a -> Bool
max, min :: a -> a -> a
compare x y = if x == y then EQ
else if x <= y then LT
else GT
14. Let’s continue:
Definition
x < y = case compare x y of { LT -> True; _ -> False }
x <= y = case compare x y of { GT -> False; _ -> True }
x > y = case compare x y of { GT -> True; _ -> False }
x >= y = case compare x y of { LT -> False; _ -> True }
max x y = if x <= y then y else x
min x y = if x <= y then x else y
15. Before moving to the second line of our quicksort we need to tell
about recursive functions definition. In mathematics we define
recursive functions in the following way:
f (n) =
1, n = 1,
n ∗ f (n − 1), n 1
In Haskell we define it by:
Definition
factorial 1 = 1
factorial n = n*factorial(n - 1)
Or, using syntax sugar:
Definition
factorial n = |n == 1 = 1
|otherwise = n*factorial(n - 1)
16. Now it’s time to look at the second line of our quicksort:
Definition
qsort [] = []
This is just a base-case of a recursively-defined function.
If we have an empty list - we don’t need to sort it - so let’s just
return it as a result.
The third line of our quicksort is:
Definition
qsort (x:xs) = (qsort lth) ++ [x] ++ (qsort gth) where
This is a recursive case. (x:xs) is a pattern matching of the input
list. Remember the second case of list definition (... a:[a]). It
makes possible to do such pattern-matching around a colon (:)
operator. This is a common trick in FP - split the list to it’s head
(element) and tail (a smaller list).
17. Let’s continue with the third line of our quicksort:
Definition
qsort (x:xs) = (qsort lth) ++ [x] ++ (qsort gth) where
Here [x] is a list of one element - x (for example - [3] or [71]).
++ - is a list concatenation operator (sometimes denoted in a
literature as ++).
Example
> [1,3] ++ [6,4,5]
[1,3,6,4,5]
(qsort lth) and (qsort gth) is a recursive call with a lists of smaller
length.
18. Let’s continue with the fourth line of our quicksort:
Definition
lth = filter (< x) xs
Here filter is one of the standard Haskell well-known higher-order
functions (HOF).
In other words - this is a function that takes another functions as
it’s [first] argument.
Example
> filter (< 3) [1,2,3,4,5]
[1,2]
> filter (>= 3) [1,2,3,4,5]
[3,4,5]
> filter (v -> (v > 1 && v <5)) [1,2,3,4,5]
[2,3,4]
19. (< x) is a section - partially applied (curried) function for the
appropriate operator (x - is the bounded (fixed) second argument).
Let’s remember Ord type class:
Definition
(<), (<=), (>), (>=) :: a -> a -> Bool
All the mentioned functions (operators) takes 2 arguments.
But if we fix (partially apply) one of the argument - the remaining
function will be of one argument which returns Bool (True | False).
Example
> :t (< 28)
(< 28) :: (Ord a, Num a) => a -> Bool
> (< 28) 27
True
> (< 28) 28
False
20. Here’s a definition of standard (Prelude) version of filter
higer-order (HOF) function:
Definition
-- ’filter’, applied to a predicate and a list,
-- returns the list of those elements that
-- satisfy the predicate, i.e.
-- > filter p xs = [ x | x <- xs, p x]
filter :: (a -> Bool) -> [a] -> [a]
filter _pred [] = []
filter pred (x:xs)
| pred x = x : filter pred xs
| otherwise = filter pred xs
21. The type declaration of filter tells us that it’s a HOF by the
bracket around the first argument:
filter :: (a -> Bool) -> ...
The second argument is a list of type a ([a])
The result is also the list of typa a which contains the same or
fewer elements than the second argument. The next line of filter
definition:
filter _pred [] = []
Is a partial definition for the case then the second argument is an
empty list.
The first argument (predicate pred) does not matter in this case.
It is usual to user the underscore symbol - for such cases.
22. The other lines of filter definition is a recursive case:
filter pred (x:xs)
| pred x = x : filter pred xs
| otherwise = filter pred xs
It consists of two parts.
The first one is for the case if predicate pred is True for the
element x. In this case we keep the element x.
x : filter pred xs
The second one (otherwise) is for for the opposite case (False).
In this case we skeep(omit) x.
filter pred xs
And process a list of the smaller size (xs) recursively.
23. We’ve just finished with one of the most famous HOF: filter. But
there are also other two ones, greately used in functional
programming.
But first let’s not break a tradition and start from example.
Let’s summarize the squares of all the natural numbers starting
from one up to n.
12 + 22 + ...n2
For the C++ this would be:
Example
1 unsigned sumnats(unsigned n)
2 {
3 unsigned result = 0;
4 for (unsigned i = 0; i < n; ++i)
5 result += i*i;
6 return result;
7 }
24. For the Haskell this function will be much simpler (AGAIN!):
Example
1 sumnats :: Int -> Int
2 sumnats n = foldr (+) 0 (map (x -> x^2) [1..n])
The comparison is:
Disclaimer #2
The total number of lines for the C++ case is 5
The total number of lines for the Haskell case is 2
The difference between C++ and Haskell version is 7 - 2 = 5
lines !!!
25. The list comprenehsion [1..n] is just a syntax sugar for the list of
successive numbers from 1 to n.
Consider the case n = 5:
Example
> [1..5]
[1,2,3,4,5]
Now let’s describe the following sub-expression:
map (x -> x^2) [1..n]
The map HOF - is for applying it’s first argument (function) to the
list.
Example
> map (x -> x*x) [1..5]
[1,4,9,16,25]
26. Here’s a more general description of map:
Definition
map f [x1, x2, ..., xn] == [f x1, f x2, ..., f xn]
map f [x1, x2, ...] == [f x1, f x2, ...]
And this is the formal (source code) definition of map:
Definition
map :: (a -> b) -> [a] -> [b]
map _ [] = []
map f (x:xs) = f x : map f xs
We pattern-match on a list constructor (:), convert matching
element using f-function and process the rest of the list (xs)
recursively.
27. The foldr (as well as foldl) is the most famous HOF - for traversing
elements of the list from right (to left) starting from a specified
element (0 in our case):
Example
> foldr (+) 0 [1,2,3,4,5]
15
> foldr (+) 0 [1,4,9,16,25]
55
Here’s a more general description of foldr:
Definition
foldr (op) x0 [x1, x2, ..., xn] ==
(x1 ’op’ (x2 ’op’ ... ’op’ (xn ’op’ x0)))
-- or, in case of associative operation ’op’:
foldr (op) x0 [x1, x2, ..., xn] ==
x1 ’op’ x2 ’op’ ... ’op’ xn ’op’ x0
28. In graphical form, foldr and foldl can be represented as:
In other words - we replace the empty list ([]) by start element and
list constructor (:) by our operation.
And this is the formal (source code) definition of foldr:
Definition
foldr :: (a -> b -> b) -> b -> [a] -> b
foldr _ z [] = z
foldr f z (x:xs) = f x (foldr f z xs)
-- foldr op x0 (x:xs) = x ’op’ (foldr op x0 xs)
29. Another sample - let’s calculate a maximum of list elements.
Traditional (C++) approach is:
Example
1 int my_max(size_t cnt, int values[])
2 {
3 int result = values[0];
4 for(size_t i = 1; i < cnt; ++i)
5 result = values[i] > result ? values[i] : r
6 return result;
7 }
The haskell version is:
Example
1 my_max :: Ord a => [a] -> a
2 my_max = foldr1 max
30. Here foldr1 is a standard Haskell derivation of foldr (using last
element of a list as a start one):
Definition
1 -- | ’foldr1’ is a variant of ’foldr’ that
2 -- has no starting value argument,
3 -- and thus must be applied to non-empty lists.
4 foldr1 :: (a -> a -> a) -> [a] -> a
5 foldr1 _ [x] = x
6 foldr1 f (x:xs) = f x (foldr1 f xs)
7 foldr1 _ [] = errorEmptyList "foldr1"
31. Fold Universality
Fold is a very universal. Map can be expressed through it:
map’ f xs = foldr ((:) . f) []) xs
Haskell allows to omit all the dupclicated arguments if they appear
at the both (left and right) side of definition:
map’ f = foldr ((:) . f) [])
This is called point-free style.
((:) . f) is a composition of list constructor (:) and
argument-function f. Function composition (.) is defined as:
(.) :: (b -> c) -> (a -> b) -> (a -> c)
(.) f g = x -> f (g x)
The last line can be also written as:
f . g = x -> f (g x)
32. Filter can be represented as:
filter’ :: (a -> Bool) -> [a] -> [a]
filter’ p = foldr (x acc -> if p x then x : acc else acc)
Note: If always have the else-clause in haskell since it’s pure
functional language (without side-effects).
33. Many list functions can be specified by a single foldr:
Example
sum = foldr (+) 0
product = foldr (∗) 1
and = foldr (∧) True
or = foldr (∨) False
maximum = foldr max (−∞)
minimum = foldr min ∞
length = foldr (λ n → 1 + n) 0
concat = foldr (++) []
34. The Bird-Meertens Formalism, devised by Richard Bird and
Lambert Meertens:
The BMF (also called Squiggol) is a calculus for deriving
programs from specifications (in a functional program setting).
Proposes algebra of List-based data structures with
map/fold/filter HOFs, composition and primitive operations.
A big class of regular loop/for calculations in imperative
languges can be easily described by BMF.
List-functions, calculated this way (homomorphisms), can be
easily parallelized (Map/Reduce).
The great introduction to Lists, Monoids, Homomorphisms (and
it’s 3 theorems) is given in russian at Folds in Intel Click Plus
article.
35. Selected Publications
Richard Bird Lambert Meertens Jeremy Gibbons
R.S. Bird, An Introduction to the theory of lists
Lambert Meertens. Algorithmics Towards programming as a
mathematical activity
Jeremy Gibbons. The Third Homomorphism Theorem
36. Safety
Consider the case - we need to describe a flock of sheep. Every
sheep has a mother and father. In C++ we usually write this:
class Sheep {
public:
std::string m_Name;
Sheep *m_pFather;
Sheep *m_pMother;
Sheep(const std::string &name)
: m_Name(name), m_pFather(NULL), m_pMother(NULL)
{}
}
And if we need to get a name of the fater we write:
std::string fater_name = aSheep.pFater->name
And this is sometimes JUST CRASH with ACCESS VIOLATION
since aSheep can be a ”Dolly-clone” without mother and/or father.
37. Safety
”Null References” are also invented by C.A.R. Hoare.
Citation
I call it my billion-dollar mistake. It was the invention of the null reference in
1965. At that time, I was designing the first comprehensive type system for
references in an object oriented language (ALGOL W).
My goal was to ensure that all use of references should be absolutely safe, with
checking performed automatically by the compiler. But I couldn’t resist the
temptation to put in a null reference, simply because it was so easy to
implement.
This has led to innumerable errors, vulnerabilities, and system crashes, which
have probably caused a billion dollars of pain and damage in the last forty years.
In recent years, a number of program analysers like PREfix and PREfast in
Microsoft have been used to check references, and give warnings if there is a
risk they may be non-null. More recent programming languages like Spec#
have introduced declarations for non-null references.
This is the solution, which I rejected in 1965.
38. Nulls at Haskell
In haskell there is no such notion as null. It uses Maybe algebraic
data type (ADT) in order to represent calculation which may
provide no any result:
Example
data Maybe a = Nothing | Just a
Here ”Maybe” is a type-constructor function (it gives a type ”a”
as an input and returns a new type ”Maybe a”).
”Nothing” and ”Just a” are value constructors.
39. Nulls at Haskell
Datatype for our sheep is:
Example
data Sheep = Sheep {
name :: String
, mother :: Maybe Sheep
, father :: Maybe Sheep
..
}
-- this will auto-generate functions:
name :: Sheep -> String
name = ...
father :: Sheep -> Maybe Sheep
father = ...
mother :: Sheep -> Maybe Sheep
mother = ...
40. Nulls at Haskell
The following function will find mothernal grandfather:
Example
matGrandf :: Sheep -> Maybe Sheep
matGrandf s = case (mother s) of
Nothing -> Nothing
Just m -> father m
Let’s try to forget about ”Nothing” case:
Example
matGrandf :: Sheep -> Maybe Sheep
matGrandf s = case (mother s) of
-- Nothing -> Nothing
Just m -> father m
41. Nulls at Haskell
Let’s compile the mentioned version:
Example
> ghc --make -Wall ... <file_name>.hs
...
Warning: Pattern match(es) are non-exhaustive
In a case alternative:
Patterns not matched: Nothing
...
We can see that the compiler warns us about incomplete case
alternatives.
Note: this works only if we are interesting in warning (-Wall
option).
42. Nulls at Haskell
But what if we need to know a more distant ancestor? The typical
solution is to use a nested case operators (or if-then-else):
Example
motPatGrand :: Sheep -> Maybe Sheep
motPatGrand s = case (mother s) of
Nothing -> Nothing
Just m -> case (father m) of
Nothing -> Nothing
Just gf -> father gf
How does Haskell deal with this issue?
The answer is - MONADS !!!
43. Do you see similarity?
Let’s look on the following very similar functions:
Example
-- father, mother :: Sheep -> Maybe Sheep
matGrandf :: Sheep -> Maybe Sheep
matGrandf s = case (mother s) of
Nothing -> Nothing
Just m -> father m
matGrandm :: Sheep -> Maybe Sheep
matGrandm s = case (mother s) of
Nothing -> Nothing
Just m -> mother m
patGrandm :: Sheep -> Maybe Sheep
patGrandm s = case (father s) of
Nothing -> Nothing
Just m -> mother m
44. Unusual functional composition
They all are ALMOST the same except having mother and father
at distinct places.
This means that we can ABSTRACT from the function specific
(mother or father which are of the same type) and think about
function composition in an UNUSUAL way.
Example (unusual functional composition)
-- father, mother :: Sheep -> Maybe Sheep
type SheepFun = Sheep -> Maybe Sheep
s_comp :: SheepFun -> SheepFun -> SheepFun
s_comp fun1 fun2 = s ->
case (fun1 s) of
Nothing -> Nothing
Just m -> fun2 m
45. Great simplification
Using our unusual composition s comp we can GREATLY simplify
our functios:
Example (great simplification)
-- father, mother :: Sheep -> Maybe Sheep
matGrandf :: Sheep -> Maybe Sheep
matGrandf = mother ’s_comp’ father
matGrandm :: Sheep -> Maybe Sheep
matGrandm = mother ’s_comp’ mother
patGrandm :: Sheep -> Maybe Sheep
patGrandm = father ’s_comp’ mother
motPatGrand :: Sheep -> Maybe Sheep
motPatGrand = mother ’s_comp’ father ’s_comp’ father
46. Why is this unusual?
Why is this kind of composition is UNUSUAL?
Let’s remember the usual function composition:
Example (usual functional composition)
(.) :: (b -> c) -> (a -> b) -> (a -> c)
(.) f g = x -> f (g x)
In a usual way (using point in Haskell) we can combine two
functions such that the input argument type (domain) of the first
is equal to the output (domain) of the other (type-variable ”b” at
the example).
Returning to our SHEEPs, we need to compose functions, domen
of the first one (Sheep) is NOT-EQUAL to the codomain of the
second (Maybe Sheep).
That’s why our sheep-function-composition is UNUSUAL.
47. Monadic functions
So, our sheep-functions (of type ”Sheep − > Maybe Sheep”) are
called monadic-functions.
For ’s comp’ Haskel uses special fish-operator (>=>).
Haskell syntax
In Haskell operator is a function named by spec-symbols only.
Regular function names are made of of alpha-numeric symbols only (first
is alpha). Mixing spec-symbols and alpha-numberic symbols is prohibited.
Operators are used in infix form by default, but can be written in prefix
form togeather with parenthesis:
plus x y = x + y
minus x y = (-) x y
Regular functions are in prefix form by default, but can be written in infix
form togeather with quotes:
mean x y = (plus x y) / 2
mean x y = (x ’plus’ y) / 2
48. Monadic fish-operator
Abstracting from ”Maybe” (replacing it by ”m”) we can write the
type of our fish operator (for our simple case) as:
(>=>) :: Monad m => (a -> m a) -> (a -> m a) -> (a -> m a)
Remember, that in our case ”a” stands for ”Sheep”, and ”m”
stands for ”Maybe”.
So, it gives two monadic functions, glues them togeather and
returns a new monadic function (all are of the same type).
In Haskell in order to be a (Monad), fish-operator MUST be
associative (for Maybe case):
(f >=> g) >=> h == f >=> (g >=> h)
Please, try to prove (or find in google) that fish is really associative
for the case of ”Maybe”.
49. Monadic fish-operator
Proof hints
Glueing maybe–monadic-functions we always propagate ”Nothing”
case (no matter at what position).
If all the values are in a ”Just x” form - we get a regular function
composition, which is known to be associative.
Taking associativeness in account we are free to omit parenthesis:
Example
motPatGrand = mother >=> father >=> father
So, monadic fish-operator (as a first approximation) forms a
semigroup at the set of monadic functions.
Algebra goes into play
From this moment we can use ALGEGRAIC methods while
operating with monads.
50. Combining monadic with non-monadic function
But how can we combine a regular and monadic function ?
Suppose we have the following function for making a brother of
the Sheep:
Example
brother :: Sheep -> Sheep
brother s = Sheep(
name(s) ++ "_brother"
mother(s)
father(s)
)
It returns a plain Sheep (not a Maybe Sheep).
So, we need a kind of CONNECTOR function (to convert from
plain Sheep to a Maybe Sheep).
51. Monadic return function
In Haskell a function named return is used for such convertion.
Example
return :: Sheep -> Maybe Sheep
return s = Just s
It gives a Sheep s and return a Just value-constructor for it.
Now we can combine our brother function with just defined
return in order to get a monadic function:
Example
monadic_brother :: Sheep -> Maybe Sheep
monadic_brother = return . brother
We just used a regular composition (.) and Haskell point-free style
here.
52. Monoid
Since return does nothing with its argument except placing it into
Maybe monad, we can easily check the following statements:
Example
fun >=> return == fun
return >=> fun == fun
In other words, return - is the identity element for monadic
fish-composition at the set of simple monadic functions.
So, our >=> and return form a Monoid (semigroup with identity
element OR group without inversibility).
Algebra goes into play
We continue using ALGEGRAIC methods while operating with
monads.
53. Correcting monadic composition
Let’s remind our regular function composition:
Example (usual functional composition)
(.) :: (b -> c) -> (a -> b) -> (a -> c)
(.) f g = x -> f (g x)
Our simplistic-version of monadic composition was:
(>=>) :: Monad m => (a -> m a) -> (a -> m a) -> (a -> m a)
Actually in Haskell, fish has more sophisticated type:
(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> (a -> m c)
There is also a flipped-version of fish-operator (similar to regular
composition):
(<=<) :: Monad m => (b -> m c) -> (a -> m b) -> (a -> m c)
54. Correcting monadic composition
So, what is a regular function composition?
Let’s call F1 a set of all the one-argument functions:
F1 = {f : A → B}
Then, composition can be treated as a partial function from
cartesian product of F1 with itself to F1.
◦ : (F1 × F1) → F1
In the same way, monadic fish composition operator is also a
partial function (not all the monadic functions can be combined
with it, but only those that match type constraints).
55. Monad type class
Taking all the above into account, the question is - ”What is a
monad in Haskell”? Let’s look at the source code:
Example
class Monad m where
-- Sequentially compose two actions, passing any value
-- produced by the first as an argument to the second.
(>>=) :: forall a b. m a -> (a -> m b) -> m b
-- Inject a value into the monadic type.
return :: a -> m a
-- Sequentially compose two actions, discarding any
-- value produced by the first, like sequencing operators
-- (such as the semicolon) in imperative languages.
(>>) :: forall a b. m a -> m b -> m b
-- Explicit for-alls so that we know what order to
-- give type arguments when desugaring
m >> k = m >>= _ -> k
...
56. Fish and Bind operators
Let’s compare the monadic bind-operator and a fish-one:
Example
-- Just to remind a Monad definition:
(>>=) :: forall a b. m a -> (a -> m b) -> m b
-- Left-to-right Kleisli composition of monads
(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> (a -> m c)
f >=> g = x -> f x >>= g
So, fish-operator is a polymorphic higher-order function, defined for
ALL the monads through the appropriate SPECIFIC bind operator.
57. Fish and Bind for Maybe
The Maybe monad in Haskell is defined as:
Example
instance Monad Maybe where
-- (>>=) :: m a -> (a -> m b) -> m b
(Just x) >>= k = k x
(Just _) >> k = k
Nothing >>= _ = Nothing
return = Just
58. Monad laws - nice version
As we told above, in order to be a monad, a programmer (not a
compiler) MUST enforce the followin LAWS for specific monad.
The nice version of monad laws uses fish-operator:
Example
1. return >=> f == f
2. f >=> return == f
3. (f >=> g) >=> h == f >=> (g >=> h)
Compare with the composition LAWS:
Example
1. id . f == f
2. f . id == f
3. (f . g) . h == f . (g . h)
What is the difference ???
59. Monad laws - ugly version
The UGLY version of the same laws is using monadic bind operator:
Example
1. return x >>= f == f x
2. mv >>= return == mv
3. (mv >>= f) >>= g == mv >>= (x -> (f x >>= g))
Ensuring the correctness of monad laws for standard/custom
monads is CRITICAL for the correctness since Haskell compiler is
free to evaluate fish/bind operators in ANY ORDER!!!
60. Monad folding
What if we need to compose a dynamic list of monadic functions?
Example
h = mf1 >=> mf2 >=> ... >=> mfN
In this case we need to use a folding function (foldr or foldl):
Example
h = foldr (>=>) return [mf1, mf2, ..., mfN]
Remember that:
return is an identity element of our monoid
fish-operator (>=>) - operation of monoid (semigroup)
monadic functions (mf1, mf2, ... mfN) - elements of monoid
S.McLane
Monad is the Monoid at the category of endofunctors.
61. List comprehensions - Intro
It’s time to remember our first example - quicksort function.
Example
qsort :: Ord a => [a] -> [a]
qsort [] = []
qsort (x:xs) = qsort [y | y <- xs, y < x] ++
[x ] ++
qsort [y | y <- xs, y >= x]
The expression in square brackets is a Haskell list comprehension.
62. Pythagorean triples
Let’s find all the positive triples such that x2 + y2 = z2.
C++0x version (n is the limit) is:
Example
void PythTriples(int limit,
std::function<void(int,int,int)> yield) {
for (int x = 1; x < limit; ++x)
for (int y = x + 1; y < limit; ++y)
for (int z = y + 1; z <= limit; ++z)
if (x*x + y*y == z*z)
yield(x, y, z);
}
int main() {
PythTriples(20, [] (int x, int y, int z) {
std::cout << x << "," << y << "," << z << "n";
});
}
63. Pythagorean triples in Haskell
Haskell version with list comprehensions is:
Example
pyth :: (Num a, Enum a) => a -> [(a, a, a)]
pyth n = [(x,y,z) | x <- [1..n], y <- [x..n], z <- [y..n],
x^2 + y^2 == z^2]
Sample session (for n = 20):
Example
> pyth 20
[(3,4,5),(5,12,13),(6,8,10),(8,15,17),(9,12,15),(12,16,20)]
List comprehensions actually is a very conveniet syntax sugar over
List Monad.
64. Pythagorean triples desugared
So, desugared version of pythagorean triples uses list monad:
Example
pyth n = do
x <- [1..n]
y <- [x..n]
z <- [y..n]
guard $ x^2 + y^2 == z^2
return (x,y,z)
Do-notation is also just a syntactic sugar with the following rules
Definition
do { x }
= x
do { x ; <stmts> }
= x >> do { <stmts> }
do { v <- x ; <stmts> }
= x >>= v -> do { <stmts> }
65. Desugared List monad
Desugared version using monadic bind operator is:
Example
import Control.Monad
pyth n =
[1..n] >>= (x ->
[x..n] >>= (y ->
[y..n] >>= (z ->
(guard $ x^2 + y^2 == z^2) >>
return (x,y,z))))
Here guard - is a monadic higher-order function:
Example
guard :: (MonadPlus m) => Bool -> m ()
guard True = return ()
guard False = mzero
66. MonadPlus
MonadPlus class extends Monad in order to support choice and
failure:
Example
class Monad m => MonadPlus m where
-- the identity of ’mplus’.
-- It should also satisfy the equations
-- mzero >>= f = mzero
-- v >> mzero = mzero
mzero :: m a
-- an associative operation
mplus :: m a -> m a -> m a
instance MonadPlus [] where
mzero = []
mplus = (++)
instance MonadPlus Maybe where
mzero = Nothing
Nothing ‘mplus‘ ys = ys
xs ‘mplus‘ _ = xs
67. List Monad
And, finally, list monad is defined as:
Example
instance Monad [] where
return x = [x]
xs >>= f = concat (map f xs)
Here return is an identity monadic function (of type a → [a]).
It just puts an argument to the list (returns a one-elemen-list).
Function f (also of a type a → [b]) is any monadic function.
It converts an argument to the list of some type (equal or not to
the type of argument).
Bind maps f over monadic value (xs list) which leads to the list of
lists, then - makes a plain version via concat function.
68. List Monad Bind example
In order to be more clear, consider example:
Example
> map (x -> [-x,x]) [1,2,3]
[[-1,1],[-2,2],[-3,3]]
> concat $ map (x -> [-x,x]) [1,2,3]
[-1,1,-2,2,-3,3]
> [1,2,3] >>= x -> [-x,x]
[-1,1,-2,2,-3,3]
Concat is defined as:
Example
-- Concatenate a list of lists.
concat :: [[a]] -> [a]
concat = foldr (++) []
69. Powerset definition
Consider the powerset - set of all subsets of the given set.
For simplicity let original set be all numbers from 0 to N-1.
For N = 4 the set will be 0,1,2,3 and its powerset:
Example
{ }
{ 3 }
{ 2 }
{ 2 3 }
{ 1 }
{ 1 3 }
{ 1 2 }
{ 1 2 3 }
{ 0 }
{ 0 3 }
{ 0 2 }
{ 0 2 3 }
{ 0 1 }
{ 0 1 3 }
{ 0 1 2 }
{ 0 1 2 3 }
70. Powerset in c++ - part 1
Another example - all subsets of the given set (powerset):
Example
void powerset(size_t s, size_t n, bool b[],
std::function<void(std::vector<size_t>)> yield){
for(size_t i = 0; i <= 1; ++i) {
b[n] = i ? true : false;
if (n < (s - 1))
powerset(s, n + 1, b, yield);
else {
std::vector<size_t> v;
for (size_t j = 0; j < s; ++j)
if (b[j])
v.push_back(j);
yield(v);
}
}
}
71. Powerset in c++ - part 2
Calling the powerset (in CPS style using C++0x lambdas):
Example
int main(void) {
size_t s = 4;
boost::scoped_array<bool> pB(new bool [s]);
powerset(s, 0, pB.get(), [] (std::vector<size_t> v) {
std::cout << "{";
std::for_each(v.begin(), v.end(), [] (size_t e) {
std::cout << " " << e;
});
std::cout << " }" << std::endl;
});
return 0;
}
72. Powerset in Haskell
In Haskell the powerset is:
Example
powerset :: [a] -> [[a]]
powerset = filterM (x -> [True, False])
-- powerset xs = filterM (x -> [True, False]) xs
Here’s a standard polymorphic monadic HOF filterM:
Example
-- This generalizes the list-based ’filter’ function.
filterM :: (Monad m) => (a -> m Bool) -> [a] -> m [a]
filterM _ [] = return []
filterM p (x:xs) = do
flg <- p x
ys <- filterM p xs
return (if flg then x:ys else ys)