Refinement Types and the bearing they *may* have on the concept of partiality, which I have always wrestled with in FP.
Original Reveal.js slides can be viewed here: http://blog.forgetfulfunctor.com/fpsyd-liquid-haskell/
The document discusses various data structures in Scala including queues and binary search trees. It describes functional queues in Scala as immutable data structures with head, tail, and enqueue operations. It also covers different implementations of queues and optimizations. For binary search trees, it explains the binary search tree property, provides a Tree class representation in Scala, and algorithms for in-order, pre-order, and post-order tree traversals along with their Scala implementations.
Talk is about simple data structures like queue and Tree and their possible implementation in Scala. It also talks about binary search trees and their traversals.
My talk at Bangalore Java Users Group. It was meant developers who want to get them started on Scala. This talk objectives was to get started on creating a project in Scala, write some code using collections and test it using ScalaTest.
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Philip Schwarz
Quicksort - a whistle-stop tour of the algorithm in five languages and four paradigms.
Programming Paradigms: Functional, Logic, Imperative, Imperative Functional
Languages: Haskell, Scala, Java, Clojure, Prolog
This document discusses Scala collections. It provides an introduction to Scala collections and code examples of using various collection types like lists, sets, tuples, maps, and options. It also covers functional combinators that can be used on collections, such as map, filter, foldLeft, and flatten.
This document introduces Scala collections and their key features:
- Collections provide a concise, safe, and fast way to process collections of data through built-in functions.
- Collections can be mutable or immutable, with immutable being the default. Mutable collections require importing specific packages.
- The core abstractions are Traversable, Iterable, and Seq, with traits like Set and Map defining specific collection types.
- Common collection types include lists, arrays, buffers, and queues - each with their own performance characteristics for different usage cases.
Functional Programming by Examples using Haskellgoncharenko
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 discusses various data structures in Scala including queues and binary search trees. It describes functional queues in Scala as immutable data structures with head, tail, and enqueue operations. It also covers different implementations of queues and optimizations. For binary search trees, it explains the binary search tree property, provides a Tree class representation in Scala, and algorithms for in-order, pre-order, and post-order tree traversals along with their Scala implementations.
Talk is about simple data structures like queue and Tree and their possible implementation in Scala. It also talks about binary search trees and their traversals.
My talk at Bangalore Java Users Group. It was meant developers who want to get them started on Scala. This talk objectives was to get started on creating a project in Scala, write some code using collections and test it using ScalaTest.
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Philip Schwarz
Quicksort - a whistle-stop tour of the algorithm in five languages and four paradigms.
Programming Paradigms: Functional, Logic, Imperative, Imperative Functional
Languages: Haskell, Scala, Java, Clojure, Prolog
This document discusses Scala collections. It provides an introduction to Scala collections and code examples of using various collection types like lists, sets, tuples, maps, and options. It also covers functional combinators that can be used on collections, such as map, filter, foldLeft, and flatten.
This document introduces Scala collections and their key features:
- Collections provide a concise, safe, and fast way to process collections of data through built-in functions.
- Collections can be mutable or immutable, with immutable being the default. Mutable collections require importing specific packages.
- The core abstractions are Traversable, Iterable, and Seq, with traits like Set and Map defining specific collection types.
- Common collection types include lists, arrays, buffers, and queues - each with their own performance characteristics for different usage cases.
Functional Programming by Examples using Haskellgoncharenko
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.
Scala collections provide a uniform approach to working with data structures. They are generic, immutable, and support higher-order functions like map and filter. The core abstractions are Traversable and Iterable, with subclasses including lists, sets, and maps. Collections aim to be object-oriented, persistent, and follow principles like the uniform return type. They allow fluent, expressive ways to transform, query, and manipulate data in a functional style.
Zippers are a design pattern in functional programming languages, such as Haskell, which provides a focus point and methods for navigating around in a functional data structure. It turns out that for any algebraic data type with one parameter, the derivative of the type is a zipper for it.
This document provides a 3-sentence summary of the given document:
The document is a tutorial introduction to high-performance Haskell that covers topics like lazy evaluation, reasoning about space usage, benchmarking, profiling, and making Haskell code run faster. It explains concepts like laziness, thunks, and strictness and shows how to define tail-recursive functions, use foldl' for a strict left fold, and force evaluation of data constructor arguments to avoid space leaks. The goal is to help programmers optimize Haskell code and make efficient use of multiple processor cores.
Slideshare hasn't imported my notes, so here's the link to the Google Presentation: https://goo.gl/Gl4Vhm
Haskell is a statically typed, non strict, pure functional programming language. It is often talked and blogged about, but rarely used commercially. This talk starts with a brief overview of the language, then explains how Haskell is evaluated and how it deals with non-determinism and side effects using only pure functions. The suitability of Haskell for real world data science is then discussed, along with some examples of its users, a small Haskell-powered visualization, and an overview of useful packages for data science. Finally, Accelerate is introduced, an embedded DSL for array computations on the GPU, and an ongoing attempt to use it as the basis for a deep learning package.
This document provides an introduction to functional programming concepts in Scala including mutability, functions as first-class citizens, closures, pattern matching, recursion, lazy vs eager evaluation, type classes, ad-hoc polymorphism, concurrency, and functional data structures. It also briefly mentions additional Scala concepts that could be covered like existential types, self types, structural typing, compile-time metaprogramming, reactive programming with Akka, and more advanced functional programming topics.
Comonads are the category-theoretic dual of monads. While monads have been found to be a very useful design pattern for structuring programs in functional languages, such as Haskell, comonads have so far failed to gain much traction. In this talk we will look at what comonads are and how they are defined in Haskell, comparing them with the Haskell definition of monads. We will then look at some specific examples of comonads and how they can be used in practical programs.
We will assume basic knowledge of Haskell, including the Monad class and common instances. No knowledge of category theory will be required.
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...Philip Schwarz
First see the problem solved using the List monad and a Scala for comprehension.
Then see the Scala program translated into Haskell, both using a do expressions and using a List comprehension.
Understand how the Scala for comprehension is desugared, and what role the withFilter function plays.
Also understand how the Haskell do expressions and List comprehension are desugared, and what role the guard function plays.
Scala code for Part 1: https://github.com/philipschwarz/n-queens-combinatorial-problem-scala-part-1
Errata: on slide 30, the resulting lists should be Haskell ones rather than Scala ones.
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit - Haskell and...Philip Schwarz
See how feeding FP workhorses map and filter with monadic steroids turns them into the intriguing mapM and filterM.
Graduate to foldM by learning how it behaves with the help of three simple yet instructive examples of its usage.
Use the powers of foldM to generate all permutations of a collection with a simple one-liner.
Exploit what you learned about foldM to solve the N-Queens Combinatorial Problem with an iterative approach rather than a recursive one.
In this presentation, You will get to know about Function Literal,Higher Order Function,Partial Function,Partial Applied Function,Nested Function,Closures.
The goal of this workshop is to introduce fundamental capabilities of R as a tool for performing data analysis. Here, we learn about the most comprehensive statistical analysis language R, to get a basic idea how to analyze real-word data, extract patterns from data and find causality.
R is a programming language and software environment for statistical analysis and graphics. It allows for effective data manipulation, storage, and graphical display. Some key features of R include being free and open source with many contributed packages, having simple yet elegant code, and the ability to perform statistical analysis and visualization. The R studio interface has components for running code in the console, editing code in the editor, and viewing outputs like plots and help documentation. Common data structures in R include vectors, matrices, lists, and data frames.
This document provides an overview of arrays in C programming. It defines an array as a variable that can store multiple values of the same type. It describes how to declare and initialize single-dimensional and multi-dimensional arrays, access array elements, pass arrays to functions, and the relationship between arrays and pointers in C. Key points covered include declaring arrays with syntax like datatype arrayName[arraySize], initializing arrays, accessing elements by index, and that arrays decay to pointers when passed to functions.
Scala is a multi-paradigm programming language that runs on the JVM. It combines object-oriented and functional programming concepts. SBT is the build tool used for Scala projects and allows for incremental compilation. Scala has a uniform approach to collections that emphasizes immutability and uses higher-order
The document provides an overview of pandas series including:
- Creation of series from arrays, dictionaries, scalar values
- Mathematical operations on series like addition, subtraction
- Functions to access series data like head(), tail(), indexing, slicing
- Examples of arithmetic operations on series using operators and methods
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.
Scala collections provide a uniform approach to working with data structures. They are generic, immutable, and support higher-order functions like map and filter. The core abstractions are Traversable and Iterable, with subclasses including lists, sets, and maps. Collections aim to be object-oriented, persistent, and follow principles like the uniform return type. They allow fluent, expressive ways to transform, query, and manipulate data in a functional style.
Zippers are a design pattern in functional programming languages, such as Haskell, which provides a focus point and methods for navigating around in a functional data structure. It turns out that for any algebraic data type with one parameter, the derivative of the type is a zipper for it.
This document provides a 3-sentence summary of the given document:
The document is a tutorial introduction to high-performance Haskell that covers topics like lazy evaluation, reasoning about space usage, benchmarking, profiling, and making Haskell code run faster. It explains concepts like laziness, thunks, and strictness and shows how to define tail-recursive functions, use foldl' for a strict left fold, and force evaluation of data constructor arguments to avoid space leaks. The goal is to help programmers optimize Haskell code and make efficient use of multiple processor cores.
Slideshare hasn't imported my notes, so here's the link to the Google Presentation: https://goo.gl/Gl4Vhm
Haskell is a statically typed, non strict, pure functional programming language. It is often talked and blogged about, but rarely used commercially. This talk starts with a brief overview of the language, then explains how Haskell is evaluated and how it deals with non-determinism and side effects using only pure functions. The suitability of Haskell for real world data science is then discussed, along with some examples of its users, a small Haskell-powered visualization, and an overview of useful packages for data science. Finally, Accelerate is introduced, an embedded DSL for array computations on the GPU, and an ongoing attempt to use it as the basis for a deep learning package.
This document provides an introduction to functional programming concepts in Scala including mutability, functions as first-class citizens, closures, pattern matching, recursion, lazy vs eager evaluation, type classes, ad-hoc polymorphism, concurrency, and functional data structures. It also briefly mentions additional Scala concepts that could be covered like existential types, self types, structural typing, compile-time metaprogramming, reactive programming with Akka, and more advanced functional programming topics.
Comonads are the category-theoretic dual of monads. While monads have been found to be a very useful design pattern for structuring programs in functional languages, such as Haskell, comonads have so far failed to gain much traction. In this talk we will look at what comonads are and how they are defined in Haskell, comparing them with the Haskell definition of monads. We will then look at some specific examples of comonads and how they can be used in practical programs.
We will assume basic knowledge of Haskell, including the Monad class and common instances. No knowledge of category theory will be required.
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...Philip Schwarz
First see the problem solved using the List monad and a Scala for comprehension.
Then see the Scala program translated into Haskell, both using a do expressions and using a List comprehension.
Understand how the Scala for comprehension is desugared, and what role the withFilter function plays.
Also understand how the Haskell do expressions and List comprehension are desugared, and what role the guard function plays.
Scala code for Part 1: https://github.com/philipschwarz/n-queens-combinatorial-problem-scala-part-1
Errata: on slide 30, the resulting lists should be Haskell ones rather than Scala ones.
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit - Haskell and...Philip Schwarz
See how feeding FP workhorses map and filter with monadic steroids turns them into the intriguing mapM and filterM.
Graduate to foldM by learning how it behaves with the help of three simple yet instructive examples of its usage.
Use the powers of foldM to generate all permutations of a collection with a simple one-liner.
Exploit what you learned about foldM to solve the N-Queens Combinatorial Problem with an iterative approach rather than a recursive one.
In this presentation, You will get to know about Function Literal,Higher Order Function,Partial Function,Partial Applied Function,Nested Function,Closures.
The goal of this workshop is to introduce fundamental capabilities of R as a tool for performing data analysis. Here, we learn about the most comprehensive statistical analysis language R, to get a basic idea how to analyze real-word data, extract patterns from data and find causality.
R is a programming language and software environment for statistical analysis and graphics. It allows for effective data manipulation, storage, and graphical display. Some key features of R include being free and open source with many contributed packages, having simple yet elegant code, and the ability to perform statistical analysis and visualization. The R studio interface has components for running code in the console, editing code in the editor, and viewing outputs like plots and help documentation. Common data structures in R include vectors, matrices, lists, and data frames.
This document provides an overview of arrays in C programming. It defines an array as a variable that can store multiple values of the same type. It describes how to declare and initialize single-dimensional and multi-dimensional arrays, access array elements, pass arrays to functions, and the relationship between arrays and pointers in C. Key points covered include declaring arrays with syntax like datatype arrayName[arraySize], initializing arrays, accessing elements by index, and that arrays decay to pointers when passed to functions.
Scala is a multi-paradigm programming language that runs on the JVM. It combines object-oriented and functional programming concepts. SBT is the build tool used for Scala projects and allows for incremental compilation. Scala has a uniform approach to collections that emphasizes immutability and uses higher-order
The document provides an overview of pandas series including:
- Creation of series from arrays, dictionaries, scalar values
- Mathematical operations on series like addition, subtraction
- Functions to access series data like head(), tail(), indexing, slicing
- Examples of arithmetic operations on series using operators and methods
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.
An overview of the Idris functional programming language. Idris has a number of interesting features such as dependent types, function totality checking and theorem proving.
This document discusses reasoning about laziness in Haskell. It explains that functions and data constructors don't evaluate their arguments until needed. This laziness allows separating producers and consumers efficiently. However, laziness can also cause problems like space leaks from unevaluated thunks. The document demonstrates techniques like using seq, bang patterns and strict data types to control evaluation order and avoid space leaks. It also discusses how to determine which arguments a function evaluates strictly.
This document discusses various topics related to Haskell and functional programming:
1. It defines functions for adding, subtracting, and multiplying quaternions. However, quaternion multiplication is not commutative, so it cannot fully implement the Num typeclass.
2. It introduces the Maybe type for handling potential failure cases in functions like division or accessing the head of an empty list.
3. It defines a Tree type for representing binary trees and functions like mapping and calculating size.
4. It generalizes the idea of mapping with the Functor typeclass, showing instances for lists, Maybe, and trees. Homework involves making the Tree type into a binary search tree and adapting it for a key-value container
The document is a cheat sheet for data wrangling with pandas, providing syntax and examples for common data wrangling tasks like creating and reshaping DataFrames, subsetting data, combining datasets, filtering and joining data, grouping data, handling missing values, and creating plots. It includes functions and methods for tasks like melting and pivoting data, sorting and ordering rows, subsetting rows and columns, merging and joining datasets, applying operations to groups and windows of data, and replacing or dropping missing values.
The document is a cheat sheet for data wrangling with pandas, providing syntax and examples for common data wrangling tasks like creating and reshaping DataFrames, subsetting data, combining datasets, filtering and joining data, grouping data, handling missing values, and creating plots. It covers topics such as creating DataFrames from lists or dictionaries, melting and pivoting data, sorting and ordering rows, subsetting rows and columns, merging datasets, and applying functions across columns or groups.
The document is a cheat sheet for data wrangling with pandas, providing syntax and methods for creating and manipulating DataFrames, reshaping and subsetting data, summarizing data, combining datasets, filtering and joining data, grouping data, handling missing values, and plotting data. Key methods described include pd.melt() to gather columns into rows, pd.pivot() to spread rows into columns, pd.concat() to append DataFrames, df.sort_values() to order rows by column values, and df.groupby() to group data.
This document provides a summary of key pandas syntax and methods for data wrangling and manipulation. It covers topics such as creating and reshaping DataFrames, subsetting data, handling missing values, summarizing data, joining datasets, and grouping and aggregating data. The cheat sheet also describes functions for vector and group-based operations, as well as window functions for rolling and expanding calculations. Overall, it serves as a concise reference guide for the main pandas techniques used in data analysis workflows.
Binary search trees have the following key properties:
1. Each node contains a value.
2. The left subtree of a node contains only values smaller than the node's value.
3. The right subtree of a node contains only values larger than the node's value.
Binary search trees allow for efficient insertion and search operations in O(log n) time due to their structure. Deletion may require rebalancing the tree to maintain the binary search tree properties.
With all of the focus on OOP and frameworks, sometimes the utilities get ignored. These modules provide us with lightweight, simple, effective solutions to everyday problems, saving us all from reinventing the wheel. This talk looks at a several of the utilities and shows some of the less common ways they can save a lot of time.
The document summarizes Donald Knuth's "dancing links" algorithm for solving exact cover problems. It describes how doubly linked lists are used to represent the constraints in exact cover problems and how covering and uncovering columns corresponds to adding and removing elements from the lists. It provides pseudocode for implementing the algorithm to solve problems like sudoku, N-queens, and their reductions to exact cover. The document is intended as an educational overview of the dancing links approach.
Data Wrangling with dplyr and tidyr Cheat SheetDr. Volkan OBAN
This document provides a cheat sheet for data wrangling techniques using the dplyr and tidyr packages in R. It outlines conventions for working with tibbles and piping syntax. Methods are presented for reshaping data between wide and long formats, tidying data into a tidy format, subsetting and selecting data, grouping and summarizing data, creating new variables, and joining data.
Grouped data frames allow dplyr functions to manipulate each group separately. The group_by() function creates a grouped data frame, while ungroup() removes grouping. Summarise() applies summary functions to columns to create a new table, such as mean() or count(). Join functions combine tables by matching values. Left, right, inner, and full joins retain different combinations of values from the tables.
The document discusses the dynamic programming approach to solving the Fibonacci numbers problem and the rod cutting problem. It explains that dynamic programming formulations first express the problem recursively but then optimize it by storing results of subproblems to avoid recomputing them. This is done either through a top-down recursive approach with memoization or a bottom-up approach by filling a table with solutions to subproblems of increasing size. The document also introduces the matrix chain multiplication problem and how it can be optimized through dynamic programming by considering overlapping subproblems.
The document discusses binary search trees and their properties. It explains that a binary search tree is a binary tree where every node's left subtree contains values less than the node's value and the right subtree contains greater values. Operations like search, insert, delete can be done in O(h) time where h is the height of the tree. The height is O(log n) for balanced trees but can be O(n) for unbalanced trees. The document also provides examples of using a binary search tree to sort a set of numbers in O(n log n) time by building the BST and doing an inorder traversal.
Is it easier to add functional programming features to a query language, or to add query capabilities to a functional language? In Morel, we have done the latter.
Functional and query languages have much in common, and yet much to learn from each other. Functional languages have a rich type system that includes polymorphism and functions-as-values and Turing-complete expressiveness; query languages have optimization techniques that can make programs several orders of magnitude faster, and runtimes that can use thousands of nodes to execute queries over terabytes of data.
Morel is an implementation of Standard ML on the JVM, with language extensions to allow relational expressions. Its compiler can translate programs to relational algebra and, via Apache Calcite’s query optimizer, run those programs on relational backends.
In this talk, we describe the principles that drove Morel’s design, the problems that we had to solve in order to implement a hybrid functional/relational language, and how Morel can be applied to implement data-intensive systems.
(A talk given by Julian Hyde at Strange Loop 2021, St. Louis, MO, on October 1st, 2021.)
RStudio is a trademark of RStudio, PBC. This document provides a cheat sheet on tidying data with the tidyr package in R. It defines tidy data as having each variable in its own column and each observation in its own row. It discusses tibbles as an enhanced data frame format and provides functions for constructing, subsetting, and printing tibbles. It also covers reshaping data through pivoting, handling missing values, expanding and completing data, and working with nested data through nesting, unnesting, and applying functions to list columns.
C++ ProgramRecursive reversal of a tree.[16] Write a method voi.pdffunkybabyindia
C++ Program:
Recursive reversal of a tree.
[16] Write a method void TreeNode::reverse() (with wrapper void Tree::reverse() ) which
recursively reverses the tree.
Solution
Answer:-
1) Traverse the given tree in inorder fashion and store all odd level nodes in an auxiliary array.
For the above example given tree, contents of array become {h, i, b, j, k, l, m, c, n, o}
2) Reverse the array. The array now becomes {o, n, c, m, l, k, j, b, i, h}
3) Traverse the tree again inorder fashion. While traversing the tree, one by one take elements
from array and store elements from array to every odd level traversed node.
For the above example, we traverse ‘h’ first in above array and replace ‘h’ with ‘o’. Then we
traverse ‘i’ and replace it with n.
Program:-
// C++ program to reverse alternate levels of a binary tree
#include
#define MAX 100
using namespace std;
// A Binary Tree node
struct Node
{
char data;
struct Node *left, *right;
};
// A utility function to create a new Binary Tree Node
struct Node *newNode(char item)
{
struct Node *temp = new Node;
temp->data = item;
temp->left = temp->right = NULL;
return temp;
}
// Function to store nodes of alternate levels in an array
void storeAlternate(Node *root, char arr[], int *index, int l)
{
// Base case
if (root == NULL) return;
// Store elements of left subtree
storeAlternate(root->left, arr, index, l+1);
// Store this node only if this is a odd level node
if (l%2 != 0)
{
arr[*index] = root->data;
(*index)++;
}
// Store elements of right subtree
storeAlternate(root->right, arr, index, l+1);
}
// Function to modify Binary Tree (All odd level nodes are
// updated by taking elements from array in inorder fashion)
void modifyTree(Node *root, char arr[], int *index, int l)
{
// Base case
if (root == NULL) return;
// Update nodes in left subtree
modifyTree(root->left, arr, index, l+1);
// Update this node only if this is an odd level node
if (l%2 != 0)
{
root->data = arr[*index];
(*index)++;
}
// Update nodes in right subtree
modifyTree(root->right, arr, index, l+1);
}
// A utility function to reverse an array from index
// 0 to n-1
void reverse(char arr[], int n)
{
int l = 0, r = n-1;
while (l < r)
{
int temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
l++; r--;
}
}
// The main function to reverse alternate nodes of a binary tree
void reverseAlternate(struct Node *root)
{
// Create an auxiliary array to store nodes of alternate levels
char *arr = new char[MAX];
int index = 0;
// First store nodes of alternate levels
storeAlternate(root, arr, &index, 0);
// Reverse the array
reverse(arr, index);
// Update tree by taking elements from array
index = 0;
modifyTree(root, arr, &index, 0);
}
// A utility function to print indorder traversal of a
// binary tree
void printInorder(struct Node *root)
{
if (root == NULL) return;
printInorder(root->left);
cout << root->data << \" \";
printInorder(root->right);
}
// Driver Program to test above functions
int main()
{
struct Node *root = newNode(\'a\');
root->left = newNode(.
Red-black trees are a self-balancing binary search tree. They ensure fast lookups, inserts, and deletes by keeping the height of the tree shallow. Insertion into a red-black tree may violate its balancing properties, so a fixup procedure is used. It recolors nodes red or black and performs rotations to ensure no more than one red link between any node and its children. This preserves the tree's balancing and keeps operations efficient.
The document discusses recursion and provides examples of recursive algorithms and data structures including arithmetic series, Fibonacci sequence, binary search, and mergesort. Recursion involves breaking a problem down into smaller sub-problems until they can be solved directly, and combining the solutions to solve the original problem. Examples demonstrate how recursion uses function calls to solve problems by dividing them into base cases and recursively calling itself on smaller instances.
Transform Your Communication with Cloud-Based IVR SolutionsTheSMSPoint
Discover the power of Cloud-Based IVR Solutions to streamline communication processes. Embrace scalability and cost-efficiency while enhancing customer experiences with features like automated call routing and voice recognition. Accessible from anywhere, these solutions integrate seamlessly with existing systems, providing real-time analytics for continuous improvement. Revolutionize your communication strategy today with Cloud-Based IVR Solutions. Learn more at: https://thesmspoint.com/channel/cloud-telephony
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j
Dr. Jesús Barrasa, Head of Solutions Architecture for EMEA, Neo4j
Découvrez les dernières innovations de Neo4j, et notamment les dernières intégrations cloud et les améliorations produits qui font de Neo4j un choix essentiel pour les développeurs qui créent des applications avec des données interconnectées et de l’IA générative.
Zoom is a comprehensive platform designed to connect individuals and teams efficiently. With its user-friendly interface and powerful features, Zoom has become a go-to solution for virtual communication and collaboration. It offers a range of tools, including virtual meetings, team chat, VoIP phone systems, online whiteboards, and AI companions, to streamline workflows and enhance productivity.
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Łukasz Chruściel
No one wants their application to drag like a car stuck in the slow lane! Yet it’s all too common to encounter bumpy, pothole-filled solutions that slow the speed of any application. Symfony apps are not an exception.
In this talk, I will take you for a spin around the performance racetrack. We’ll explore common pitfalls - those hidden potholes on your application that can cause unexpected slowdowns. Learn how to spot these performance bumps early, and more importantly, how to navigate around them to keep your application running at top speed.
We will focus in particular on tuning your engine at the application level, making the right adjustments to ensure that your system responds like a well-oiled, high-performance race car.
When deliberating between CodeIgniter vs CakePHP for web development, consider their respective strengths and your project requirements. CodeIgniter, known for its simplicity and speed, offers a lightweight framework ideal for rapid development of small to medium-sized projects. It's praised for its straightforward configuration and extensive documentation, making it beginner-friendly. Conversely, CakePHP provides a more structured approach with built-in features like scaffolding, authentication, and ORM. It suits larger projects requiring robust security and scalability. Ultimately, the choice hinges on your project's scale, complexity, and your team's familiarity with the frameworks.
Graspan: A Big Data System for Big Code AnalysisAftab Hussain
We built a disk-based parallel graph system, Graspan, that uses a novel edge-pair centric computation model to compute dynamic transitive closures on very large program graphs.
We implement context-sensitive pointer/alias and dataflow analyses on Graspan. An evaluation of these analyses on large codebases such as Linux shows that their Graspan implementations scale to millions of lines of code and are much simpler than their original implementations.
These analyses were used to augment the existing checkers; these augmented checkers found 132 new NULL pointer bugs and 1308 unnecessary NULL tests in Linux 4.4.0-rc5, PostgreSQL 8.3.9, and Apache httpd 2.2.18.
- Accepted in ASPLOS ‘17, Xi’an, China.
- Featured in the tutorial, Systemized Program Analyses: A Big Data Perspective on Static Analysis Scalability, ASPLOS ‘17.
- Invited for presentation at SoCal PLS ‘16.
- Invited for poster presentation at PLDI SRC ‘16.
Utilocate offers a comprehensive solution for locate ticket management by automating and streamlining the entire process. By integrating with Geospatial Information Systems (GIS), it provides accurate mapping and visualization of utility locations, enhancing decision-making and reducing the risk of errors. The system's advanced data analytics tools help identify trends, predict potential issues, and optimize resource allocation, making the locate ticket management process smarter and more efficient. Additionally, automated ticket management ensures consistency and reduces human error, while real-time notifications keep all relevant personnel informed and ready to respond promptly.
The system's ability to streamline workflows and automate ticket routing significantly reduces the time taken to process each ticket, making the process faster and more efficient. Mobile access allows field technicians to update ticket information on the go, ensuring that the latest information is always available and accelerating the locate process. Overall, Utilocate not only enhances the efficiency and accuracy of locate ticket management but also improves safety by minimizing the risk of utility damage through precise and timely locates.
WhatsApp offers simple, reliable, and private messaging and calling services for free worldwide. With end-to-end encryption, your personal messages and calls are secure, ensuring only you and the recipient can access them. Enjoy voice and video calls to stay connected with loved ones or colleagues. Express yourself using stickers, GIFs, or by sharing moments on Status. WhatsApp Business enables global customer outreach, facilitating sales growth and relationship building through showcasing products and services. Stay connected effortlessly with group chats for planning outings with friends or staying updated on family conversations.
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j
Dr. Jesús Barrasa, Head of Solutions Architecture for EMEA, Neo4j
Découvrez les dernières innovations de Neo4j, et notamment les dernières intégrations cloud et les améliorations produits qui font de Neo4j un choix essentiel pour les développeurs qui créent des applications avec des données interconnectées et de l’IA générative.
SOCRadar's Aviation Industry Q1 Incident Report is out now!
The aviation industry has always been a prime target for cybercriminals due to its critical infrastructure and high stakes. In the first quarter of 2024, the sector faced an alarming surge in cybersecurity threats, revealing its vulnerabilities and the relentless sophistication of cyber attackers.
SOCRadar’s Aviation Industry, Quarterly Incident Report, provides an in-depth analysis of these threats, detected and examined through our extensive monitoring of hacker forums, Telegram channels, and dark web platforms.
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...kalichargn70th171
A dynamic process unfolds in the intricate realm of software development, dedicated to crafting and sustaining products that effortlessly address user needs. Amidst vital stages like market analysis and requirement assessments, the heart of software development lies in the meticulous creation and upkeep of source code. Code alterations are inherent, challenging code quality, particularly under stringent deadlines.
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxrickgrimesss22
Discover the essential features to incorporate in your Winzo clone app to boost business growth, enhance user engagement, and drive revenue. Learn how to create a compelling gaming experience that stands out in the competitive market.
Mobile App Development Company In Noida | Drona InfotechDrona Infotech
Looking for a reliable mobile app development company in Noida? Look no further than Drona Infotech. We specialize in creating customized apps for your business needs.
Visit Us For : https://www.dronainfotech.com/mobile-application-development/
6. First we learn about Maybe, adulterate the type to add a rug
to sweep the unwanted kernel under.
head' :: [a] -> Maybe a
head' (x : _) = Just x
head' [] = Nothing
tail' :: [a] -> Maybe [a]
tail' (_ : xs) = Just xs
tail' [] = Nothing
7. We have abstractions to propagate things like Maybe to the
end of the control flow:
class Functor f where
fmap :: (a -> b) -> f a -> f b
class (Functor f) => Applicative f where
pure :: a -> f a
(<*>) :: f (a -> b) -> f a -> f b
liftA2
:: (Applicative f)
=> (a -> b -> c)
-> f a -> f b -> f c
class Monad m where
return :: a -> m a
(>>=) :: m a -> (a -> m b) -> m b
8. But this is just a case of an unwanted pattern, rather than
adulterate the output type, we could refine the input type:
data NonEmpty a = a :| [a]
nonEmpty :: [a] -> Maybe (NonEmpty a)
nonEmpty (x : xs) = Just $ x :| xs
nonEmpty [] = Nothing
head' :: NonEmpty a -> a
head' (x :| _) = x
tail' :: NonEmpty a -> [a]
tail' (_ :| xs) = xs
9. FUNCTOR
And using the same machinery we can lift these simpler
total functions up to the more complicated types:
headl :: [a] -> Maybe a
headl = fmap head' . nonEmpty
taill :: [a] -> Maybe [a]
taill = fmap tail' . nonEmpty
12. LENS &
TRAVERSALS
fromList :: [a] -> Either [b] (NonEmpty a)
fromList = maybe (Left []) Right . nonEmpty
toList :: NonEmpty a -> [a]
toList (x :| xs) = x : xs
_NonEmpty :: Prism [a] [b] (NonEmpty a) (NonEmpty b)
_NonEmpty = prism toList fromList
dropTail :: NonEmpty a -> NonEmpty a
dropTail (x :| _) = x :| []
-- Provided you are happy with the "do nothing" response
-- for values in the kernel of fromList
over _NonEmpty
:: (NonEmpty a -> NonEmpty b)
-> [a] -> [b]
13. SO....
We have a lot of tools to lift functions on simpler types into
functions on more complex types.
This all sounds great, so where does it go wrong?
15. A BINARY TREE
data Tree a =
Leaf
| Node a (Tree a) (Tree a)
16. RED-BLACK
TREE
data Colour = Red | Black
data RBTree a =
Leaf
| Node Colour a (RBTree a) (RBTree a)
17. OH WAIT!
Invariants:
1. Red nodes have no Red Children
2. All paths from the root node to the leaves have the same
number of black nodes
18. PROPERTIES
This is a common use for properties, write up your
properties that check that the invariants are valid in the
output.
Write up your Arbitrary instance for your type that
produces values that satisfy the invariant.
19. Sometimes, writing up code that generates the invariant
satisfying values ends up being very similar to the code
you are testing...
On top of that concern, you have to worry about the
coverage of the invariant satisfying subset.
20. insert
:: (Ord a)
=> a
-> RBTree a
-> RBTree a
balance
:: Colour
-> a
-> RBTree a
-> RBTree a
-> RBTree a
21. LET'S REFINE
data Colour = Red | Black
data RBTree a =
Leaf
| Node Colour a (RBTree a) (RBTree a)
22. BAM!
-- Ignoring Invariant 2 since we only looking at inserts
data RedNode a = RedNode a (BlackNode a) (BlackNode a)
-- technically, the root node is supposed to be black, so this would
-- represent a red black tree in its final state.
data BlackNode a =
Leaf
| BlackNode a (RedBlack a) (RedBlack a)
data RedBlack a = R (RedNode a) | B (BlackNode a)
23. Oh, and while we are inserting a value into the tree, the tree
can be in an intermediate state where Invariant 1 is broken
at the root:
-- This is assumed to be representing a Red Node
-- at the root
data Invariant1Broken a =
LeftRedChild a (RedNode a) (BlackNode a)
| RightRedChild a (BlackNode a) (RedNode a)
data InsertState a =
Ok (RedBlack a)
| Broken (Invariant1Broken a)
24. Wooo! Alright, now lets go rewrite those two simple yet
incredibly bug prone functions!
25. BEFORE
insert
:: (Ord a)
=> a
-> RBTree a
-> RBTree a
balance
:: Colour
-> a
-> RBTree a
-> RBTree a
-> RBTree a
26. AFTER
balanceblackl :: a -> InsertState a -> RedBlack a -> RedBlack a
balanceblackr :: a -> RedBlack a -> InsertState a -> RedBlack a
fixBroken :: InsertState a -> BlackNode a
ins :: (Ord a) => a -> RedBlack a -> InsertState a
insBlack :: (Ord a) => a -> BlackNode a -> RedBlack a
insRed :: (Ord a) => a -> RedNode a -> InsertState a
joinRedl :: a -> RedBlack a -> BlackNode a -> InsertState a
joinRedr :: a -> BlackNode a -> RedBlack a -> InsertState a
insert :: (Ord a) => a -> BlackNode a -> BlackNode a
27. When the compiler finally released me I had realised I hadn't
eaten for 5 days.
But I don't have a problem.
28. The Rabbit hole goes further with Invariant 2 and deletes,
with DataKinds or GADTs.
The deletes involve leaving the tree in an intermediate
state where invariant 2 is broken.
Not going there in this talk.
30. So whats the problem here?
What's the difference between the [a] / NonEmpty a case?
31. All of the types could be injected into RBTree a much like
NonEmpty a can be injected into [a].
But theres a conceivable use for [a], values exist.
Other than implementing the core operations, users of
the of the data structure should never encounter values
that break the invariants.
32. REFINING TYPES
So far when I "refined" a type, I had to write up a
completely new distinct type.
Conversions between all these different types can be
potentially inefficient.
To "refine" [a], had to throw away the [] and build
NonEmpty a from a again.
33. We almost always use Type constructors to adulterate types
(except for Const and Identity)
34. So could we get more mileage from our types if we could
qualify our types to restrict or refine them instead of
adulterating them?
35. type RedNode a = { t : RBTree a | ??? }
type BlackNode a = { t : RBTree a | ??? }
type RedBlack a = { t : RBTree a | ??? }
type InsertState a = { t : RBTree a | ??? }
39. Haha, goodness me no.
You can see my very very very early attempt at using
DataKinds and GADTs to do it here
And a recent experiment with Liquid Types that doesn't
quite work yet here.
40. BINOMIAL
TREES
A primitive from which Binomial heaps are built:
data BinomialTree a = BinomialTree a [a]
Defined inductively as follows:
Binomial tree of Rank 0 is a singleton node.
A binomial tree of rank r + 1 is formed by linking two
binomial trees of rank r, with one becoming a child of the
other.
41. MEASURES
Liquid Haskell lets you define simple functions to use in
constraints. They can't return functions though.
{-@
measure binTreeRank :: BinomialTree a -> Int
binTreeRank (BinomialTree x cs) = len cs
@-}
42. REFINED TYPES
Or Liquid Types (Logically Qualified Data Types).
Similar to Subset Types in Coq.
{-@ type BinomialTreeN a N = {t : BinomialTree a | (binTreeRank t) = N} @-}
43. INVARIANTS
The inductive definition results in the following invariant:
The list of children is ordered by decreasing rank, with
each element 1 rank higher than the next...
44. Encode invariants into the type:
data BinomialTreeList a =
Nil
| Cons (BinomialTreeList a) (BinomialTree a)
{-@
measure listlen :: BinomialTreeList a -> Int
listlen (Nil) = 0
listlen (Cons xs x) = 1 + (listlen xs)
@-}
{-@ invariant {v : BinomialTreeList a | (listlen v) >= 0} @-}
{-@
type BinomialTreeListN a N = {ts : BinomialTreeList a | (listlen ts) = N}
@-}
-- Invariant here
{-@
data BinomialTreeList [listlen] a =
Nil
| Cons (ts :: BinomialTreeList a)
(t :: BinomialTreeListN a {(listlen ts)})
@-}
45. Let's store the rank in the structure and add an invariant for
that also:
data BinomialTree a = BinomialTree Int a (BinomialTreeList a)
{-@
measure binTreeRank :: BinomialTree a -> Int
binTreeRank (BinomialTree r x cs) = r
@-}
{-@
data BinomialTree a =
BinomialTree (r :: Int) (x :: a) (cs :: BinomialTreeListN a {r})
@-}
46. Can now provide guarantees on the outputs of functions
that are statically checked:
{-@ binlength :: t : BinomialTreeList a -> {x : Int | x = (listlen t)} @-}
binlength :: BinomialTreeList a -> Int
binlength Nil = 0
binlength (Cons ts _) = 1 + binlength ts
{-@ rank :: v : BinomialTree a -> {x : Int | x = (binTreeRank v)} @-}
rank :: BinomialTree a -> Int
rank (BinomialTree r _ _) = r
-- rank (BinomialTree _ _ cs) = binlength cs
-- rank _ = 0
47. Verify the inductive definition is preserved by our
implementation of the core operations:
-- | Singleton node defined to have rank 0
{-@ singletonTree :: a -> BinomialTreeN a {0} @-}
singletonTree :: a -> BinomialTree a
singletonTree x = BinomialTree 0 x Nil
-- | Rank r + 1 tree is created by linking together two rank r trees.
{-@
link
:: (Ord a)
=> w : BinomialTree a
-> z : BinomialTreeN a {(binTreeRank w)}
-> BinomialTreeN a {1 + (binTreeRank w)}
@-}
link :: BinomialTree a -> BinomialTree a -> BinomialTree a
link w@(BinomialTree rw x ws) z@(BinomialTree rz y zs)
| x < y = BinomialTree (rw + 1) x (Cons ws z)
| otherwise = BinomialTree (rz + 1) y (Cons zs w)
49. PROS
Don't have to manipulate proofs in parallel with program
values.
Some of the expressive capacity of Dependent Types
50. LIMITATIONS 1
Only some of the expressive capacity of Dependent Types
Can use any SMT solver backend apparently, but z3 is the
only with a reliable enough reputation
z3 is not free (Non-Commercial Research use only)
Using an SMT solver is a little "black boxy", not sure I
would ever want it in the compiler, don't know if that will
ever take off
Then again, I didn't think the IPod was going to be a big
deal.
51. LIMITATIONS 2
If refined types rule out specific patterns (e.g Red Black
trees), fails exhaustivity checking in GHC since the
function is effectively partial as far as GHC is concerned.
A lot of the time, expressing
properties/invariants/constraints is really just as
challenging as doing so in the existing type system.
So I don't think we have solved the Type complexity
problem yet.
At the moment its like a separate type system running in
parallel, gets a little schizophrenic.
Terrible error messages
52. {-@ binlength :: t : BinomialTreeList a -> {x : Int | x = (listlen t)} @-}
binlength :: BinomialTreeList a -> Int
binlength Nil = 0
binlength (Cons ts _) = 2 + binlength ts
src/Data/Binomial.hs:75:26-41: Error: Liquid Type Mismatch
Inferred type
VV : Int | (VV == (?c + ?a))
not a subtype of Required type
VV : Int | (VV == (listlen ?b))
In Context
ts : (BinomialTreeList a) | ((listlen ts) >= 0)
?b : (BinomialTreeList a) | ((listlen ?b) >= 0)
?a : Int | (?a == (listlen ts))
?c : Int | (?c == (2 : int))
53. REFERENCES
AND FURTHER
READING
Z3
N. Vazou, E. L. Seidel, R. Jhala, D. Vytiniotis, and S. Peyton-
Jones. Refinement types for Haskell
Try Liquid Haskell - An Online Interactive Liquid Haskell
Demo