This document discusses functional programming concepts like referential transparency and monads. It describes how to represent input/output operations as a monadic type in a functional way. Specifically, it shows how to define an IO monad that allows sequencing effects, while avoiding side effects. To enable tail recursion and avoid stack overflows, the IO monad is represented as an algebraic data type, allowing effects to be interpreted in a trampolined manner. An example program demonstrates how this allows safely executing an infinite loop of IO operations.
Functions in C++, this presentation will cover the following topics
• Functions
• Functions Basics
• Overloaded functions
o Different numbers of arguments
o Different kinds of arguments
Revision Fucntion overloading
• Inline functions
• Default arguments
1. Inline functions are small functions whose code is inserted at the call site instead of generating a function call. This avoids overhead of function calls but increases code size.
2. Function overloading allows different functions to have the same name but different parameters. The compiler determines which version to call based on argument types.
3. C++ classes allow defining data types that bundle together data members and member functions that can access them. Classes support data hiding and inheritance.
High order functions are functions that either take other functions as parameters or return functions. They allow functions to be passed into other functions as arguments and support abstraction. Some key advantages are that they can reduce program size, accelerate development for large programs, and have zero runtime cost in many cases by supporting abstraction and code reuse through passing functions as arguments.
Functions allow programmers to structure C++ programs into modular segments of code to perform individual tasks. There are two types of functions: library functions and user-defined functions. User-defined functions are defined using a return type, function name, and parameters. Functions can be called by value or by reference and can also be inline, recursive, or friend functions.
The document discusses implementation of stacks. It describes stacks as linear data structures that follow LIFO principles. Key stack operations like push and pop are outlined. Stacks are often implemented using arrays or linked lists. Examples of stack applications include recursion handling, expression evaluation, parenthesis checking, and backtracking problems. Conversion from infix to postfix notation using a stack is also demonstrated.
This chapter discusses input and output (I/O) in C++ programs. It introduces I/O streams as sequences of bytes or characters that move between sources and destinations. The standard input stream cin is used to extract data from the keyboard and the standard output stream cout is used to send output to the screen. Various I/O functions are described, including extraction operator >> to read data into variables from cin, and insertion operator << to write data from variables to cout. The chapter also covers file I/O, input/output formatting, and an example program that calculates movie ticket sales and a donation amount.
C++ functions presentation by DHEERAJ KATARIADheeraj Kataria
The document discusses C++ functions. It defines what a function is and describes the different types of C++ functions including standard and user-defined functions. It explains the structure of C++ functions including the function header, signature, and body. It provides examples of defining, declaring, implementing and calling functions. It also discusses topics like function parameters, scope of variables, inline functions, and building libraries.
This document provides an overview of the key concepts covered in Chapter 2 of the C++ Programming textbook. These include basic C++ program components like functions, data types, arithmetic operators, and input/output statements. It also discusses programming fundamentals like declaring variables, writing comments, using preprocessor directives, and properly structuring a C++ program with a main function. An example is provided to demonstrate how to write a program that converts between feet/inches and centimeters.
Functions in C++, this presentation will cover the following topics
• Functions
• Functions Basics
• Overloaded functions
o Different numbers of arguments
o Different kinds of arguments
Revision Fucntion overloading
• Inline functions
• Default arguments
1. Inline functions are small functions whose code is inserted at the call site instead of generating a function call. This avoids overhead of function calls but increases code size.
2. Function overloading allows different functions to have the same name but different parameters. The compiler determines which version to call based on argument types.
3. C++ classes allow defining data types that bundle together data members and member functions that can access them. Classes support data hiding and inheritance.
High order functions are functions that either take other functions as parameters or return functions. They allow functions to be passed into other functions as arguments and support abstraction. Some key advantages are that they can reduce program size, accelerate development for large programs, and have zero runtime cost in many cases by supporting abstraction and code reuse through passing functions as arguments.
Functions allow programmers to structure C++ programs into modular segments of code to perform individual tasks. There are two types of functions: library functions and user-defined functions. User-defined functions are defined using a return type, function name, and parameters. Functions can be called by value or by reference and can also be inline, recursive, or friend functions.
The document discusses implementation of stacks. It describes stacks as linear data structures that follow LIFO principles. Key stack operations like push and pop are outlined. Stacks are often implemented using arrays or linked lists. Examples of stack applications include recursion handling, expression evaluation, parenthesis checking, and backtracking problems. Conversion from infix to postfix notation using a stack is also demonstrated.
This chapter discusses input and output (I/O) in C++ programs. It introduces I/O streams as sequences of bytes or characters that move between sources and destinations. The standard input stream cin is used to extract data from the keyboard and the standard output stream cout is used to send output to the screen. Various I/O functions are described, including extraction operator >> to read data into variables from cin, and insertion operator << to write data from variables to cout. The chapter also covers file I/O, input/output formatting, and an example program that calculates movie ticket sales and a donation amount.
C++ functions presentation by DHEERAJ KATARIADheeraj Kataria
The document discusses C++ functions. It defines what a function is and describes the different types of C++ functions including standard and user-defined functions. It explains the structure of C++ functions including the function header, signature, and body. It provides examples of defining, declaring, implementing and calling functions. It also discusses topics like function parameters, scope of variables, inline functions, and building libraries.
This document provides an overview of the key concepts covered in Chapter 2 of the C++ Programming textbook. These include basic C++ program components like functions, data types, arithmetic operators, and input/output statements. It also discusses programming fundamentals like declaring variables, writing comments, using preprocessor directives, and properly structuring a C++ program with a main function. An example is provided to demonstrate how to write a program that converts between feet/inches and centimeters.
This document provides information on functions in C and C++. It discusses the main components of functions including definition, declaration, prototypes, arguments, return values, scope, and recursion. It also covers function categories, nested functions, default arguments, inline functions, function overloading, and differences between calling functions by value versus reference in C++. Overall, the document serves as a tutorial on functions and their usage in C and C++ programming.
Python Programming | JNTUA | UNIT 2 | Conditionals and Recursion | FabMinds
This document summarizes key concepts from lectures 9-11 on conditionals and recursion in Python programming. It discusses logical operators, relational operators, boolean expressions, floor division, modulus, conditional execution using if/else statements, chained and nested conditionals. Recursion is defined as a function calling itself and examples of valid and infinite recursion are provided. The document also covers taking keyboard input in Python using the input function.
C++ functions require prototypes that specify the return type and parameters. Function overloading allows multiple functions to have the same name but different signatures. Default arguments allow functions to be called without providing trailing arguments. Inline functions expand the function body at the call site for small functions to reduce overhead compared to regular function calls.
Actors and functional_reactive_programmingDiego Alonso
Slides from my presentation in the Typelevel Summit held in Lausanne, on the 14th of June 2019.
It introduces an implementation of Functional Reactive Programming, using an analogy with actors.
This document discusses functions in C++. It defines a function as having an output type, name, and arguments within parentheses. Functions can be called by passing arguments to the function name. Functions can also be called by reference by passing the address of a variable. Some important mathematical functions are provided in the C++ math library and their Fortran equivalents are shown.
Why functional programming and category theory strongly mattersPiotr Paradziński
Abstractions of Category Theory to define abstractions (Functor, Applicative, Monad, Comonad, Coyoneda) commonly used in functional programming (FP). Using definitions from Category Theory to reason about modular and composable design. Examples based on Haskell papers: Functional pearls translated to Scala.
Intro to Functional Reactive Programming In ScalaDiego Alonso
An overview and introduction to the Functional Reactive Programming paradigm, including Arrowised FRP, and a small peek at a simplified implementation of AFRP in Scala based on Monadic Stream Functions.
Given at Scala eXchange on 13th of December 2018.
The document discusses the different types of operators in C++, including unary, binary, ternary, arithmetic, logical, comparison, assignment, bitwise, and special operators like scope resolution (::), endl, and setw. It provides examples of how each operator is used, such as increment/decrement for unary, addition/subtraction for binary, conditional operator ?: for ternary, and manipulating bits with bitwise operators. The document also explains how scope resolution allows accessing global variables from inner blocks and how endl and setw are used for formatting output displays.
Function overloading in C++ allows defining multiple functions with the same name as long as they have different parameters. This enables functions to perform different tasks based on the types of arguments passed. An example demonstrates defining multiple area() functions, one taking a radius and the other taking length and breadth. Inline functions in C++ avoid function call overhead by expanding the function code at the call site instead of jumping to another location. Demonstrated with an inline mul() and div() example.
Types of C++ functions:
Standard functions
User-defined functions
C++ function structure
Function signature
Function body
Declaring and Implementing C++ functions
It tells about functions in C++,Types,Use,prototype,declaration,Arguments etc
function with
A function with no parameter and no return value
A function with parameter and no return value
A function with parameter and return value
A function without parameter and return value
Call by value and address
The document discusses stacks and their implementation and applications. It defines a stack as a linear data structure for temporary storage where elements can only be inserted or deleted from one end, called the top. Stacks follow the LIFO (last in, first out) principle. Stacks have two main operations - push, which inserts an element, and pop, which removes the top element. Stacks can be implemented using arrays or linked lists. Common applications of stacks include reversing strings, checking matching parentheses, and converting infix, postfix, and prefix expressions.
This document presents information on Polish notation and describes a program to evaluate arithmetic expressions in Polish notation. It includes an introduction to Polish notation and how it simplifies expressions by placing the operator before operands. The program uses arrays and structures as stacks to evaluate expressions in Polish notation by pushing and popping elements. It handles various cases like exponential, multiplication, division, addition and subtraction operations. The conclusion discusses how Polish notation simplifies complex expressions to make evaluation easier for compilers.
Explains the basic concepts of Category Theory, useful terminology to help understand the literature, and why it's so relevant to software engineering.
The document discusses functions in C++. It defines functions as modular pieces that divide programs into more manageable components. It describes function components like modules, functions, classes, and function calls. It provides examples of math library functions and how to define, call, and prototype functions. It also covers function parameters, return types, and scope rules for local variables and storage classes.
The document discusses functions in C++. It covers standard and user-defined functions, value-returning and void functions, formal and actual parameters, and how to define, declare, and call functions. It also discusses scope of identifiers, value vs reference parameters, function overloading, and functions with default parameters.
Here is a potential solution to the problem in C++:
#include <iostream>
using namespace std;
int main() {
int num1, num2, num3;
cout << "Enter three numbers: ";
cin >> num1 >> num2 >> num3;
int total = num1 + num2 + num3;
float average = total / 3.0;
cout << "The numbers entered were: " << num1 << ", " << num2 << ", " << num3 << endl;
cout << "Their average is: " << average;
return 0;
}
Some key points:
- Use cin to input the 3 numbers from the
The document discusses IO resource management (IORM) on Oracle Exadata. IORM governs and prioritizes IO requests to Exadata storage servers when databases are consolidated on Exadata. It describes the IORM architecture which uses categories, inter-database plans, and intra-database plans to allocate IO resources across consumer groups and databases. The document also provides details on monitoring IORM metrics using tools like CellCLI and analyzing cellsrv dump files.
Presentation by John Peterson at RMH Field Care Audit on 1/18/12. videos are posted on youtube.com/4docmontey
http://youtu.be/ahCxJ5vEcF0
http://youtu.be/Av0IJ-THnIE
This document provides an overview of EZ-IO insertion for pediatric patients. It begins by stating the learning objectives, which are to understand the indications, contraindications, complications and steps for EZ-IO insertion. It then provides information on why IO access is needed when vascular access is difficult, the indications and contraindications for EZ-IO placement, and potential complications. Components of the EZ-IO system and how to select the appropriate needle set based on weight are described. Anatomical landmarks and steps for insertion are outlined, and additional resources like videos are provided for further learning. The objectives of an in-person class are stated to be practicing EZ-IO placement in a task trainer and discussing any
The document discusses intraosseous (IO) infusion, which provides vascular access by inserting a needle into the bone marrow space. IO access is useful when intravenous access is not possible. The document covers IO anatomy, indications, contraindications, needles, devices, and procedures. It describes commonly used sites like the proximal tibia in pediatrics and distal tibia in adults. Manual insertion and use of devices like the FAST-1, Bone Injection Gun (BIG), and EZ-IO are outlined. IO access provides rapid delivery of fluids, drugs, and blood samples equivalent to intravenous routes.
This document provides information on functions in C and C++. It discusses the main components of functions including definition, declaration, prototypes, arguments, return values, scope, and recursion. It also covers function categories, nested functions, default arguments, inline functions, function overloading, and differences between calling functions by value versus reference in C++. Overall, the document serves as a tutorial on functions and their usage in C and C++ programming.
Python Programming | JNTUA | UNIT 2 | Conditionals and Recursion | FabMinds
This document summarizes key concepts from lectures 9-11 on conditionals and recursion in Python programming. It discusses logical operators, relational operators, boolean expressions, floor division, modulus, conditional execution using if/else statements, chained and nested conditionals. Recursion is defined as a function calling itself and examples of valid and infinite recursion are provided. The document also covers taking keyboard input in Python using the input function.
C++ functions require prototypes that specify the return type and parameters. Function overloading allows multiple functions to have the same name but different signatures. Default arguments allow functions to be called without providing trailing arguments. Inline functions expand the function body at the call site for small functions to reduce overhead compared to regular function calls.
Actors and functional_reactive_programmingDiego Alonso
Slides from my presentation in the Typelevel Summit held in Lausanne, on the 14th of June 2019.
It introduces an implementation of Functional Reactive Programming, using an analogy with actors.
This document discusses functions in C++. It defines a function as having an output type, name, and arguments within parentheses. Functions can be called by passing arguments to the function name. Functions can also be called by reference by passing the address of a variable. Some important mathematical functions are provided in the C++ math library and their Fortran equivalents are shown.
Why functional programming and category theory strongly mattersPiotr Paradziński
Abstractions of Category Theory to define abstractions (Functor, Applicative, Monad, Comonad, Coyoneda) commonly used in functional programming (FP). Using definitions from Category Theory to reason about modular and composable design. Examples based on Haskell papers: Functional pearls translated to Scala.
Intro to Functional Reactive Programming In ScalaDiego Alonso
An overview and introduction to the Functional Reactive Programming paradigm, including Arrowised FRP, and a small peek at a simplified implementation of AFRP in Scala based on Monadic Stream Functions.
Given at Scala eXchange on 13th of December 2018.
The document discusses the different types of operators in C++, including unary, binary, ternary, arithmetic, logical, comparison, assignment, bitwise, and special operators like scope resolution (::), endl, and setw. It provides examples of how each operator is used, such as increment/decrement for unary, addition/subtraction for binary, conditional operator ?: for ternary, and manipulating bits with bitwise operators. The document also explains how scope resolution allows accessing global variables from inner blocks and how endl and setw are used for formatting output displays.
Function overloading in C++ allows defining multiple functions with the same name as long as they have different parameters. This enables functions to perform different tasks based on the types of arguments passed. An example demonstrates defining multiple area() functions, one taking a radius and the other taking length and breadth. Inline functions in C++ avoid function call overhead by expanding the function code at the call site instead of jumping to another location. Demonstrated with an inline mul() and div() example.
Types of C++ functions:
Standard functions
User-defined functions
C++ function structure
Function signature
Function body
Declaring and Implementing C++ functions
It tells about functions in C++,Types,Use,prototype,declaration,Arguments etc
function with
A function with no parameter and no return value
A function with parameter and no return value
A function with parameter and return value
A function without parameter and return value
Call by value and address
The document discusses stacks and their implementation and applications. It defines a stack as a linear data structure for temporary storage where elements can only be inserted or deleted from one end, called the top. Stacks follow the LIFO (last in, first out) principle. Stacks have two main operations - push, which inserts an element, and pop, which removes the top element. Stacks can be implemented using arrays or linked lists. Common applications of stacks include reversing strings, checking matching parentheses, and converting infix, postfix, and prefix expressions.
This document presents information on Polish notation and describes a program to evaluate arithmetic expressions in Polish notation. It includes an introduction to Polish notation and how it simplifies expressions by placing the operator before operands. The program uses arrays and structures as stacks to evaluate expressions in Polish notation by pushing and popping elements. It handles various cases like exponential, multiplication, division, addition and subtraction operations. The conclusion discusses how Polish notation simplifies complex expressions to make evaluation easier for compilers.
Explains the basic concepts of Category Theory, useful terminology to help understand the literature, and why it's so relevant to software engineering.
The document discusses functions in C++. It defines functions as modular pieces that divide programs into more manageable components. It describes function components like modules, functions, classes, and function calls. It provides examples of math library functions and how to define, call, and prototype functions. It also covers function parameters, return types, and scope rules for local variables and storage classes.
The document discusses functions in C++. It covers standard and user-defined functions, value-returning and void functions, formal and actual parameters, and how to define, declare, and call functions. It also discusses scope of identifiers, value vs reference parameters, function overloading, and functions with default parameters.
Here is a potential solution to the problem in C++:
#include <iostream>
using namespace std;
int main() {
int num1, num2, num3;
cout << "Enter three numbers: ";
cin >> num1 >> num2 >> num3;
int total = num1 + num2 + num3;
float average = total / 3.0;
cout << "The numbers entered were: " << num1 << ", " << num2 << ", " << num3 << endl;
cout << "Their average is: " << average;
return 0;
}
Some key points:
- Use cin to input the 3 numbers from the
The document discusses IO resource management (IORM) on Oracle Exadata. IORM governs and prioritizes IO requests to Exadata storage servers when databases are consolidated on Exadata. It describes the IORM architecture which uses categories, inter-database plans, and intra-database plans to allocate IO resources across consumer groups and databases. The document also provides details on monitoring IORM metrics using tools like CellCLI and analyzing cellsrv dump files.
Presentation by John Peterson at RMH Field Care Audit on 1/18/12. videos are posted on youtube.com/4docmontey
http://youtu.be/ahCxJ5vEcF0
http://youtu.be/Av0IJ-THnIE
This document provides an overview of EZ-IO insertion for pediatric patients. It begins by stating the learning objectives, which are to understand the indications, contraindications, complications and steps for EZ-IO insertion. It then provides information on why IO access is needed when vascular access is difficult, the indications and contraindications for EZ-IO placement, and potential complications. Components of the EZ-IO system and how to select the appropriate needle set based on weight are described. Anatomical landmarks and steps for insertion are outlined, and additional resources like videos are provided for further learning. The objectives of an in-person class are stated to be practicing EZ-IO placement in a task trainer and discussing any
The document discusses intraosseous (IO) infusion, which provides vascular access by inserting a needle into the bone marrow space. IO access is useful when intravenous access is not possible. The document covers IO anatomy, indications, contraindications, needles, devices, and procedures. It describes commonly used sites like the proximal tibia in pediatrics and distal tibia in adults. Manual insertion and use of devices like the FAST-1, Bone Injection Gun (BIG), and EZ-IO are outlined. IO access provides rapid delivery of fluids, drugs, and blood samples equivalent to intravenous routes.
The document discusses input/output (I/O) interfaces. An I/O interface is required for communication between the CPU, I/O devices, and memory. It performs data buffering, control and timing, and error detection. There are two main techniques for I/O interfacing - memory mapped I/O and I/O mapped I/O. Programmed I/O is an approach where the CPU polls I/O devices by checking their status periodically to see when operations complete.
Simple IO Monad in 'Functional Programming in Scala'Philip Schwarz
The document defines an IO monad for representing computations with side effects in Scala. The IO trait defines map and flatMap methods to allow sequencing of effectful computations. Functions like ReadLine and PrintLine are defined to interact with the console. A temperature conversion program is implemented using the IO monad, separating the pure computation from executing side effects.
Monads are a typeclass for defining imperative languages. The monad typeclass allows for sequencing of operations through flatMap and lifting of values using point. For the IO monad, flatMap sequences IO operations while point lifts values into the IO context. This allows imperative-style code to be written in a pure functional style. An interpreter is then used to actually execute the side effects by pattern matching on the IO data type. With a Monad instance defined for IO using flatMap and point, code that performs IO can be written using for comprehensions for cleaner sequencing of operations.
Algebraic Thinking for Evolution of Pure Functional Domain ModelsDebasish Ghosh
The focus of the talk is to emphasize the importance of algebraic thinking when designing pure functional domain models. The talk begins with the definition of an algebra as consisting of a carrier type, a set of operations/functions and a set of laws on those operations. Using examples from the standard library, the talk shows how thinking of abstractions in terms of its algebra is more intuitive than discussing its operational semantics. The talk also discusses the virtues of parametricity and compositionality in designing proper algebras.
Algebras are compositional and help build larger algebras out of smaller ones. We start with base level types available in standard libraries and compose larger programs out of them. We take a real life use case for a domain model and illustrate how we can define the entire model using the power of algebraic composition of the various types. We talk about how to model side-effects as pure abstractions using algebraic effects. At no point we will talk about implementations.
At the end of the talk we will have a working model built completely out of the underlying algebra of the domain language.
Functional Programming Patterns for the Pragmatic ProgrammerRaúl Raja Martínez
In this talk we will see a pragmatic approach to building a purely functional architecture that delivers cohesive functional components.
We will cover functional patterns such as Free Monads, Transformers, Kleisli arrows, dependently typed checked exceptions
and types as well as how they can be glued together to achieve pure functions that are composable, context free, dependently injectable and testable.
Dome project and code with instructions to run it can be found at:
https://github.com/47deg/func-architecture
The document provides an overview of the ZIO library, which provides purely functional data structures and abstractions for effectful programs using monads. It describes ZIO's IO data type, which represents effectful programs that may fail, run forever, or produce a value. It also covers ZIO concepts like Refs (immutable references), Promises (asynchronous values that can be set once), and Queues (asynchronous FIFO queues for producers and consumers).
The document provides an introduction to functional programming with F#. It discusses configuring the environment, the basics of the F# language, and building a text adventure game. Some key points covered include: the differences between functional and object-oriented programming; defining values, functions, and types in F#; pattern matching; working with lists, sequences, and other data structures; and applying concepts like mapping, filtering, and piping to collections. The document concludes by proposing a final exercise to build a text adventure game using the functional programming concepts discussed.
Pure Functional Programming provides concise summaries of the key points in 3 sentences or less:
Pure functional programming aims for referential transparency, totality, and determinism by treating functions as mathematical objects. This allows reasoning about programs using equational logic. Effects like I/O are modeled with types like IO that describe computations without running them. Functional programs execute by interpreting values of effect types, allowing pure code to safely interact with impure systems.
The document discusses functional programming concepts like the free monad, which represents a computation as an abstract syntax tree (AST) plus an interpreter. A free monad separates the "what" of a computation, expressed as an AST, from the "how", defined by an interpreter. This allows defining reusable computations without tying them to a particular implementation. The free monad is constructed freely from a functor and gives a monad without extra work. It can be used to sequence computations and interpret them in different ways by providing a natural transformation from the functor to a monad.
After 10 years of Object Orientated Java, 2 years of Functional Programming in Scala was enough to convince me that I could never switch back. But why? The answer is simple: Functional Scala lets you think less. It reduces the number of moving parts you need to hold in your head, lets you stay focussed and saves your mental stack from overflowing.
In this talk I'll show you how to stop treating Scala as a better Java and start exploring the world of Functional Programming. I'll use code examples to demonstrate a four step path that'll let you ease yourself into the world of Functional Programming while continuing to deliver production quality code.
With each step we'll learn a new technique, and understand how it leaves you with less to think about: Hopefully this talk will convince you that Functional Scala leads to code that's easier to hold in your head, and leave you excited about learning a new paradigm.
Introduces the functional programming ideas of Functor, Apply, Applicative And Monad. Shows how to implement each in Scala with Scalaz and how to validate the implementation using property based test using specs2 and scalacheck.
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.
Blazing Fast, Pure Effects without Monads — LambdaConf 2018John De Goes
Effect monads like IO are the way functional programmers interact with the real world. Yet, monadic effects in programming languages like Scala often perform poorly compared to their Haskell counterparts—as much as 10x slower in some benchmarks. In this presentation, John A. De Goes, author of the Scalaz 8 effect system, dredges up an old paper to cast new light on the question of how to model effects, and comes to the surprising conclusion that in Scala, monads may not be the fastest way to model purely functional effects. Join John as he shows a new model of effects that offers performance improvements without sacrificing the wonderful purity that functional programmers rely on to reason about their software.
Scala, Haskell and LISP are examples of programming languages using the functional programming paradigm. Join us in this TechTalk to know why functional programming is so important, how to implement some of its core concepts in your existing programming languages, and how functional programming inspired Google's Map Reduce, Twitter's Algebird, and many other technologies.
By Mohammad Ghabboun - Senior Software Engineer, SOUQ.com
Functional Programming and Haskell - TWBR Away Day 2011Adriano Bonat
Explains why functional programming is back and shows some features from Haskell that are being ported to other languages. Presented at ThoughtWorks Brazil Away Day 2011.
How to start functional programming (in Scala): Day1Taisuke Oe
Functional programming involves composing computations like functions in a modular way. Scala supports both functional and object-oriented paradigms. Functions in Scala can be composed through methods like andThen and compose. Higher order functions allow functions to take other functions as arguments or return values. Pure functions always return the same output for the same inputs and avoid side effects. The Monoid typeclass abstracts the concepts of combining elements of a type and providing a default value, allowing new folding behaviors to be defined for types through implicit values. This allows behaviors to be extended to existing types without modifying them.
Advanced Tagless Final - Saying Farewell to FreeLuka Jacobowitz
This document discusses techniques for optimizing programs written using the tagless final pattern without losing its benefits. It presents an approach called "interpreting twice" - extracting optimization information during a first interpretation and using it to define an optimized interpreter. An example optimizes a key-value store program by parallelizing lookups, deduplicating actions, and avoiding redundant lookups. The document also discusses using FunctorK and Mainecoon to transform interpreters between monads, ensuring stack safety by interpreting to a Free monad, and generalizing optimizations using the Sphynx framework.
The document summarizes Ibis, an open source Python framework for data analysis that provides a high-level language for expressing data transformations and analytics independently of backend execution engines like Pandas or Spark. It introduces Ibis by comparing different approaches to scaling data science workflows from Pandas on a single machine to distributed systems. It then demonstrates how to express the same data preparation and analysis logic in Ibis and have it execute on different backends like Pandas or PySpark without code changes. The document shows how Ibis compilers translate expressions to backend-specific code to enable seamless transition between backends.
This document discusses functional programming (FP) and its benefits compared to object-oriented programming (OOP). It defines FP as programming with pure functions that have no side effects. The document explores eliminating side effects through techniques like separating function concerns and returning descriptions of side effects rather than executing them. It also covers FP concepts like higher order functions, recursion, and data types like Option for handling errors/exceptions. The goal is to introduce FP techniques and when each paradigm (FP vs OOP) is best suited.
Programs are composed from a series of computation steps. Standardizing those steps and how they are chained simplifies both the development and maintenance of applications.
Monads are the abstractions that help do just that. Functions are all one needs a computation building blocks, as they can be lifted to abstractions that hide complexity.
Most important New features of Oracle 23c for DBAs and Developers. You can get more idea from my youtube channel video from https://youtu.be/XvL5WtaC20A
What is Augmented Reality Image Trackingpavan998932
Augmented Reality (AR) Image Tracking is a technology that enables AR applications to recognize and track images in the real world, overlaying digital content onto them. This enhances the user's interaction with their environment by providing additional information and interactive elements directly tied to physical images.
GraphSummit Paris - The art of the possible with Graph TechnologyNeo4j
Sudhir Hasbe, Chief Product Officer, Neo4j
Join us as we explore breakthrough innovations enabled by interconnected data and AI. Discover firsthand how organizations use relationships in data to uncover contextual insights and solve our most pressing challenges – from optimizing supply chains, detecting fraud, and improving customer experiences to accelerating drug discoveries.
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.
Revolutionizing Visual Effects Mastering AI Face Swaps.pdfUndress Baby
The quest for the best AI face swap solution is marked by an amalgamation of technological prowess and artistic finesse, where cutting-edge algorithms seamlessly replace faces in images or videos with striking realism. Leveraging advanced deep learning techniques, the best AI face swap tools meticulously analyze facial features, lighting conditions, and expressions to execute flawless transformations, ensuring natural-looking results that blur the line between reality and illusion, captivating users with their ingenuity and sophistication.
Web:- https://undressbaby.com/
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.
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.
Hand Rolled Applicative User ValidationCode KataPhilip Schwarz
Could you use a simple piece of Scala validation code (granted, a very simplistic one too!) that you can rewrite, now and again, to refresh your basic understanding of Applicative operators <*>, <*, *>?
The goal is not to write perfect code showcasing validation, but rather, to provide a small, rough-and ready exercise to reinforce your muscle-memory.
Despite its grandiose-sounding title, this deck consists of just three slides showing the Scala 3 code to be rewritten whenever the details of the operators begin to fade away.
The code is my rough and ready translation of a Haskell user-validation program found in a book called Finding Success (and Failure) in Haskell - Fall in love with applicative functors.
DDS Security Version 1.2 was adopted in 2024. This revision strengthens support for long runnings systems adding new cryptographic algorithms, certificate revocation, and hardness against DoS attacks.
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
SMS API Integration in Saudi Arabia| Best SMS API ServiceYara Milbes
Discover the benefits and implementation of SMS API integration in the UAE and Middle East. This comprehensive guide covers the importance of SMS messaging APIs, the advantages of bulk SMS APIs, and real-world case studies. Learn how CEQUENS, a leader in communication solutions, can help your business enhance customer engagement and streamline operations with innovative CPaaS, reliable SMS APIs, and omnichannel solutions, including WhatsApp Business. Perfect for businesses seeking to optimize their communication strategies in the digital age.
Artificia Intellicence and XPath Extension FunctionsOctavian Nadolu
The purpose of this presentation is to provide an overview of how you can use AI from XSLT, XQuery, Schematron, or XML Refactoring operations, the potential benefits of using AI, and some of the challenges we face.
E-commerce Development Services- Hornet DynamicsHornet Dynamics
For any business hoping to succeed in the digital age, having a strong online presence is crucial. We offer Ecommerce Development Services that are customized according to your business requirements and client preferences, enabling you to create a dynamic, safe, and user-friendly online store.
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Crescat
Crescat is industry-trusted event management software, built by event professionals for event professionals. Founded in 2017, we have three key products tailored for the live event industry.
Crescat Event for concert promoters and event agencies. Crescat Venue for music venues, conference centers, wedding venues, concert halls and more. And Crescat Festival for festivals, conferences and complex events.
With a wide range of popular features such as event scheduling, shift management, volunteer and crew coordination, artist booking and much more, Crescat is designed for customisation and ease-of-use.
Over 125,000 events have been planned in Crescat and with hundreds of customers of all shapes and sizes, from boutique event agencies through to international concert promoters, Crescat is rigged for success. What's more, we highly value feedback from our users and we are constantly improving our software with updates, new features and improvements.
If you plan events, run a venue or produce festivals and you're looking for ways to make your life easier, then we have a solution for you. Try our software for free or schedule a no-obligation demo with one of our product specialists today at crescat.io
What is Master Data Management by PiLog Groupaymanquadri279
PiLog Group's Master Data Record Manager (MDRM) is a sophisticated enterprise solution designed to ensure data accuracy, consistency, and governance across various business functions. MDRM integrates advanced data management technologies to cleanse, classify, and standardize master data, thereby enhancing data quality and operational efficiency.
1. Functional I/O and Effects
Or, if a Monad folds in a functional forest, does it make an effect?
Dylan Forciea
Oseberg
February 28, 2017
2. Topics
• What does it mean for a language to be functional?
• Creating a type to represent IO operations
• Adding monoid operations to the IO type
• Adding monad operations to the IO type
• How a naïve approach for executing the monad is insufficient, and how
trampolines can fix it
3. What is a functional programming language?
• Functions as first class objects?
• Declarative rather than imperative?
• Recursion rather than loops?
4. ReferentialTransparency
• Yes!
• But ReferentialTransparency is also key to some advantages of functional
programming
• Any expression can be replaced with its value without changing the
meaning of the program
• This alludes to the fact that you should avoid side effects
5. Example of ReferentialTransparency
def average(x: Int, y: Int, z: Int): Int = (x + y + z) / 3
average(1, 2, 3)
(1 + 2 + 3) / 3
(6) / 3
2
Running this a second time with the same input values will always return the
same result
6. Counterexample of ReferentialTransparency
var cumulativeValue: Int = 0
var numberSummed: Int = 0
def cumulativeAverage(x: Int): Int = {
numberSummed = numberSummed + 1
cumulativeValue += x
cumulativeValue / numberSummed
}
cumulativeAverage(10)
cumulativeValue = 10, numberSummed = 1, result = (10/1) = 10
cumulativeAverage(20)
cumulativeValue = 30, numberSummed = 2, result = (30/2) = 15
cumulativeAverage(20)
cumulativeValue = 50, numberSummed = 3, result = (50/3) = 16
8. ReferentialTransparency and IO
def addOneToUserInput(): Int = scala.io.StdIn.readInt() + 1
The return value of executing this function will be different depending on what
the user inputs!
9. Wrapping IO in aType
• Separate IO into a type and define actions inside
• Denotes which pieces of the code are actions
• Defer running an action until later
• Describe a program containing effects purely functionally, and then run it
10. Wrapping IO in aType
trait IO[A] { def run: A }
def PrintLine(msg: String): IO[Unit] = new IO[Unit] { def run: Unit =
println(msg) }
PrintLine(“Hello, world!”).run
Hello, world!
11. How do we run a sequence of these actions?
• Make it a monoid, of course!
• What was a monoid, again?
12. Monoid Refresher
• A monoid is a combination of:
• Some type, A
• A seed (or "zero") for that type
• An associative binary operator.
• Concretely:
trait Monoid[A] {
def op(a1:A, a2: A): A
def zero: A
}
• In addition to the associativity of op, for any A the following must hold:
• op(a, zero) == a == op(zero, a)
13. Monoid Refresher Example
• For integer addition:
object IntMonoid extends Monoid[Int] {
def op(a: Int, b: Int): Int = a + b
def zero: Int = 0
}
• You can use operations like fold to combine these:
• List(1, 2, 3).fold(IntMonoid.zero)(IntMonoid.op)
• (((0 + 1) + 2) + 3) = 6
14. IO as a Monoid
trait IO[A] { self =>
def run:A
def ++[B](io: IO[B]): IO[B] = new IO[B] { def run: B = { self.run; io.run } }
}
object IO {
def zero: IO[Unit] = new IO[Unit] { def run: Unit = { } }
def ++[A, B](io1: IO[A], io2: IO[B]): IO[B] = io1 ++ io2
}
15. IO Monoid Example Usage
(PrintLine("Hello!") ++ PrintLine("World!")).run
Hello!
World!
val ioList = List(PrintLine("One"), PrintLine("Two"), PrintLine("Three"))
ioList.fold(IO.zero)(IO.++).run
One
Two
Three
16. That’s great, but…
• We can chain together output effects
• But, how can we actually perform any operations on input effects?
• Monads!
• Wait, another one of those big words…
17. Monad refresher
• Monads provide two operations:
• def map[B](f:A => B): IO[B]
• def flatMap[B](f:A => IO[B]): IO[B]
18. Monad refresher
• map transforms a value from domainA to a value from domain B inside the
monad
• flatMap transforms a value from domain A into a Monad containing a value
from domain B, and then returns a monad containing a value from domain B
19. How does this help?
• map takes the result of an IO monad and perform computations on the value
• flatMap takes the result of an IO monad, and then perform IO for output
• Like control flow for the IO “program”
20. IO as a Monad
trait IO[A] { self =>
def run:A
def ++[B](io: IO[B]): IO[B] = new IO[B] { def run: B = { self.run; io.run } }
def map[B](f: A => B): IO[B] = new IO[B] { def run: B = f(self.run) }
def flatMap[B](f: A => IO[B]): IO[B] =
new IO[B] { def run: B = f(self.run).run }
}
def PrintLine(msg: String): IO[Unit] =
new IO[Unit] { def run: Unit = println(msg) }
def GetLine(): IO[String] =
new IO[String] { def run: String = scala.io.StdIn.readLine() }
21. Lets put it together!
PrintLine("Type a number")
.flatMap(_ => GetLine())
.map(s => s.toInt)
.map(i => i + 1)
.flatMap(r => PrintLine(r.toString))
.run
Type a number
1
2
22. Can’t mix and match
GetLine().toInt + 1
<console>:15: error: value toInt is not a member of IO[String]
GetLine().toInt + 1
23. Some useful operations
def doWhile[A](a: IO[A])(cond: A => IO[Boolean]): IO[Unit] = for {
a1 <- a
ok <- cond(a1)
_ <- if (ok) doWhile(a)(cond) else IO.zero
} yield ()
def forever[A, B](a: IO[A]): IO[B] = a flatMap(_ => forever(a))
24. Houston, we have a problem!
forever(PrintLine("Hello")).run
Hello
Hello
…
<Stack Overflow!>
• What happened?!
25. Not tail recursive
def flatMap[B](f: A => IO[B]): IO[B] = new IO[B] { def run: B = f(self.run).run }
def forever[B](a: IO[A]): IO[B] = a flatMap(_ => forever(a))
• forever keeps on calling flatMap
• Every time flatMap is called, we end up one level lower in recursion
• Since the function definition says we need to keep track of the results of
f(this.run) to call run on it, we keep on adding on to the call stack every time
26. How do we fix this?
• Use Trampolining
• Create a series ofAlgebraic DataTypes (ADTs) to describe how the
operation will run
• We can make running our IO monad operations tail recursive
• First things first…
• What is tail recursion?
• What is anADT?
27. Tail Recursion
• Don’t want to keep track of state after calling function recursively
• If the last function run is the recursive call, then it is in tail position
• We can skip adding a stack frame
28. Tail recursion example
def factorial(n: BigInt): BigInt = if (n == 0) 1 else n * factorial(n-1)
def factorial_tailrec(n: BigInt): BigInt = {
def factorial1(n: BigInt, acc: BigInt): BigInt =
if (n == 0)
acc
else
factorial1(n - 1, n * acc)
factorial1(n, 1)
}
29. Algebraic DataTypes
• This is a data type that can be one of several things, and each thing can
contain a defined set of data
• We can use pattern matching to perform operations on the ADT
• This is probably more apparent if we just give an example…
30. List ADT definition
sealed trait List[+A]
case class Cons[+A](head: A, tail: List[A]) extends List[A]
case object Nil extends List[Nothing]
31. List ADT Pattern Matching
val a = Cons(1, Nil)
val b = Cons(2, a)
val c = Cons(3, b)
def add(list: List[Int]): Int =
list match {
case Cons(head, tail) => head + add(tail)
case Nil => 0
}
add(c)
6 3 2 1
32. Describing IO monad operations with an ADT
sealed trait IO[A] { self =>
def flatMap[B](f: A => IO[B]): IO[B] = FlatMap(self, f)
def map[B](f: A => B): IO[B] = flatMap(a => (Return(f(a))))
}
case class Return[A](a: A) extends IO[A]
case class Suspend[A](resume: () =>A) extends IO[A]
case class FlatMap[A, B](sub: IO[A], k: A => IO[B]) extends IO[B]
def PrintLine(s: String): IO[Unit] = Suspend(() => Return(println(s)))
def GetLine: IO[String] = Suspend(() => scala.io.StdIn.readLine())
33. Our example from earlier!
PrintLine("Type a number")
.flatMap(_ => GetLine)
.map(s => s.toInt)
.map(i => i + 1)
.flatMap(r => PrintLine(r.toString))
Suspend
PrintLine
Prompt
34. Our example from earlier!
PrintLine("Type a number")
.flatMap(_ => GetLine)
.map(s => s.toInt)
.map(i => i + 1)
.flatMap(r => PrintLine(r.toString))
Suspend
PrintLine
Prompt
FlatMap
Suspend
GetLine
35. Our example from earlier!
PrintLine("Type a number")
.flatMap(_ => GetLine)
.map(s => s.toInt)
.map(i => i + 1)
.flatMap(r => PrintLine(r.toString))
Suspend
PrintLine
Prompt
FlatMap
Suspend
GetLine
Return
s.toInt
FlatMap
36. Our example from earlier!
PrintLine("Type a number")
.flatMap(_ => GetLine)
.map(s => s.toInt)
.map(i => i + 1)
.flatMap(r => PrintLine(r.toString))
Suspend
PrintLine
Prompt
FlatMap
Suspend
GetLine
Return
s.toInt
Return
i + 1
FlatMap
FlatMap
37. Our example from earlier!
PrintLine("Type a number")
.flatMap(_ => GetLine)
.map(s => s.toInt)
.map(i => i + 1)
.flatMap(r => PrintLine(r.toString))
Suspend
PrintLine
Prompt
FlatMap
Suspend
GetLine
Return
s.toInt
Return
i + 1
Suspend
PrintLine
Result
FlatMap
FlatMap
FlatMap
38. Now we need the Interpreter…
def run[A](io: IO[A]): A = io match {
case Return(a) => a
case Suspend(r) => r()
case FlatMap(x, f) => x match {
case Return(a) => run(f(a))
case Suspend(r) => run(f(r()))
case FlatMap(y, g) => run(y.flatMap(a => g(a).flatMap(f)))
}
}
44. Run the example
Suspend
GetLine
Return
s.toInt
Return
i + 1
Suspend
PrintLine
Result
FlatMap
FlatMap
FlatMap
PrintLine("Type a number")
.flatMap(_ => GetLine)
.map(s => s.toInt)
.map(i => i + 1)
.flatMap(r => PrintLine(r.toString))
45. Run the example
Return
s.toInt
Return
i + 1
Suspend
PrintLine
Result
FlatMap
FlatMap
PrintLine("Type a number")
.flatMap(_ => GetLine)
.map(s => s.toInt)
.map(i => i + 1)
.flatMap(r => PrintLine(r.toString))
46. Run the example
Return
i + 1
Suspend
PrintLine
Result
FlatMap
PrintLine("Type a number")
.flatMap(_ => GetLine)
.map(s => s.toInt)
.map(i => i + 1)
.flatMap(r => PrintLine(r.toString))
50. Takeaways
• Like a Free Monad! (A story for another day…)
• You don’t have to use the same interpreter... you can represent IO as ADTs
and not perform IO at all
• Effects are purposeful and partitioned off within a type
• Bonus – it happens to be a monad!
51. Other libraries
• Slick
• Describe SQL operations
• Execute them once they are prepared
• Akka Streams
• Describe a dataflow with a graph
• Push data through the graph components
• In Scala, this is an advanced flavor of the IO monad described here
53. References
• Functional Programming in Scala, Chiusano and Bjarnason
• https://www.slideshare.net/InfoQ/purely-functional-io - Nice presentation
by Runar Bjarnason
• http://blog.higher-order.com/assets/scalaio.pdf
Editor's Notes
Testability
It is much easier to create test cases when the same inputs predictably result in the same output
Promotes parallel programming
When the results will be the same for a computation regardless of what is externally happening, parallelizing computations becomes almost trivial
Can enable optimization of code
For example, in Haskell, which is purely functional, execution order of functions in an expression is not defined and may not even be run at all (called laziness)
This is safe to do because the compiler knows that running one function cannot change the result of running another function later if the inputs are the same
We can separate IO into a type and define actions inside
Allows us to denote which pieces of the code are actions
We can also defer running an action until later
Then, writing a program involves describing a program containing effects purely functionally, and then executing it
map takes a value in domain A inside the type and performs a function to transform it to domain B
Think of it like the Monad is a box that contains a value, and you are running a function to transform that value
flatMap is like map, except the function returns another monad wrapping the result, and this is flattened down to one level
Think of it like map, except you run a function that transforms that value into another box of the same type inside with a value inside it
Then you take the item out of the inside box and make it the top level value
map allows us to take the result of an IO monad as an input and perform computations on the value
flatMap allows us to take the result of an IO monad as an input, and then perform IO for output
Think of it like control flow for the IO “program”
Pretty abstract, right? Let’s take a look at how it gets put together…
We use a concept called Trampolining
Rather than actually making the function call, we create a series of Algebraic Data Types (ADTs) to describe how the operation will run
Using this, we can make running our IO monad operations tail recursive
First things first…
What is tail recursion?
What is an ADT?
We are trying to make it so when we call our function recursively, we don’t have to keep track of the result of the computation to combine it with another operation
If the very last function call is the recursive call, then it is in tail position and we can skip adding a stack frame
This approach is similar to a general concept called Free Monads, but that is a subject for another day…
You don’t have to use the same interpreter... you can represent IO as ADTs and not perform IO at all
Maybe just always return the same string
Maybe write to a file rather than to the console instead
Effects are purposeful and partitioned off within a type (which happens to be a monad!)
These are not side effects!
Describe the computation using an ADT purely functionally
Execute the ADT with an intepreter