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.
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...Philip Schwarz
The document discusses implementing aggregation functions inductively using recursion or folding. It explains that aggregation functions like sum, count, max can be defined inductively with a base case for empty sequences and a recursive step to process additional elements. Implementing functions recursively risks stack overflow for long inputs, but tail-recursion and accumulator tricks can help avoid this. Folds provide an alternative to recursion for defining aggregations by processing sequences from left to right or right to left.
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3Philip Schwarz
(download for picture-perfect quality) Follow along as Trampolining is used to overcome Stack Overflow issues with the simple IO monad, deepening you understanding of the IO monad in the process. See Game of Life IO actions migrated to the Cats Effect IO monad, which is trampolined in its flatMap evaluation.
Errata:
slide 33: "impure factorial function" should be "initial factorial function"
slide 34: there is a pointless short vertical bar inside a speech bubble
slide 39: "it is till annoying" should be "it is still annoying"
slide 44: "values that we are interested" should be "values that we are interested in"
(download for flawless quality) Learn more about the canonical definition of the Applicative typeclass by looking at a great Haskell validation example by Chris Martin and Julie Moronuki - Then see it translated to Scala.
Scala code: https://github.com/philipschwarz/applicative-functor-part-2-scala
--- Errata ---
Slide #41: the definition of the right shark operator contains a defect - see https://twitter.com/philip_schwarz/status/1416127396659478539
The document discusses functional programming and pattern matching. It provides examples of using pattern matching in functional programming to:
1. Match on algebraic data types like lists to traverse and operate on data in a recursive manner. Pattern matching allows adding new operations easily by adding new patterns.
2. Use pattern matching in variable declarations to destructure data like tuples and case class objects.
3. Perform pattern matching on function parameters to selectively apply different logic based on the patterns, like filtering even numbers from a list. Everything can be treated as values and expressions in functional programming.
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.
1. Functions allow programmers to break programs into smaller, self-contained subprograms, making code more modular and reusable.
2. There are four types of functions: those with no arguments and no return value, no arguments but a return value, arguments but no return value, and arguments with a return value.
3. Functions can be user-defined or library functions provided in standard libraries that perform common tasks like input/output and mathematics. Functions must be declared, defined, and called properly in a program.
Implicit conversions and parameters allow interoperability between types in Scala. Implicit conversions define how one type can be converted to another type, and are governed by rules around marking, scope, ambiguity, and precedence. The compiler tries to insert implicit conversions in three places: to match an expected type, to convert a receiver before a method selection, and to provide missing implicit parameters. Debugging implicits involves explicitly writing out conversions to see where errors occur.
In this tutorial the reader can learn about data fitting, interpolation and approximation in Scilab. Interpolation is very important in industrial applications for data visualization and metamodeling.
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...Philip Schwarz
The document discusses implementing aggregation functions inductively using recursion or folding. It explains that aggregation functions like sum, count, max can be defined inductively with a base case for empty sequences and a recursive step to process additional elements. Implementing functions recursively risks stack overflow for long inputs, but tail-recursion and accumulator tricks can help avoid this. Folds provide an alternative to recursion for defining aggregations by processing sequences from left to right or right to left.
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3Philip Schwarz
(download for picture-perfect quality) Follow along as Trampolining is used to overcome Stack Overflow issues with the simple IO monad, deepening you understanding of the IO monad in the process. See Game of Life IO actions migrated to the Cats Effect IO monad, which is trampolined in its flatMap evaluation.
Errata:
slide 33: "impure factorial function" should be "initial factorial function"
slide 34: there is a pointless short vertical bar inside a speech bubble
slide 39: "it is till annoying" should be "it is still annoying"
slide 44: "values that we are interested" should be "values that we are interested in"
(download for flawless quality) Learn more about the canonical definition of the Applicative typeclass by looking at a great Haskell validation example by Chris Martin and Julie Moronuki - Then see it translated to Scala.
Scala code: https://github.com/philipschwarz/applicative-functor-part-2-scala
--- Errata ---
Slide #41: the definition of the right shark operator contains a defect - see https://twitter.com/philip_schwarz/status/1416127396659478539
The document discusses functional programming and pattern matching. It provides examples of using pattern matching in functional programming to:
1. Match on algebraic data types like lists to traverse and operate on data in a recursive manner. Pattern matching allows adding new operations easily by adding new patterns.
2. Use pattern matching in variable declarations to destructure data like tuples and case class objects.
3. Perform pattern matching on function parameters to selectively apply different logic based on the patterns, like filtering even numbers from a list. Everything can be treated as values and expressions in functional programming.
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.
1. Functions allow programmers to break programs into smaller, self-contained subprograms, making code more modular and reusable.
2. There are four types of functions: those with no arguments and no return value, no arguments but a return value, arguments but no return value, and arguments with a return value.
3. Functions can be user-defined or library functions provided in standard libraries that perform common tasks like input/output and mathematics. Functions must be declared, defined, and called properly in a program.
Implicit conversions and parameters allow interoperability between types in Scala. Implicit conversions define how one type can be converted to another type, and are governed by rules around marking, scope, ambiguity, and precedence. The compiler tries to insert implicit conversions in three places: to match an expected type, to convert a receiver before a method selection, and to provide missing implicit parameters. Debugging implicits involves explicitly writing out conversions to see where errors occur.
In this tutorial the reader can learn about data fitting, interpolation and approximation in Scilab. Interpolation is very important in industrial applications for data visualization and metamodeling.
(video of these slides available here http://fsharpforfunandprofit.com/fppatterns/)
In object-oriented development, we are all familiar with design patterns such as the Strategy pattern and Decorator pattern, and design principles such as SOLID.
The functional programming community has design patterns and principles as well.
This talk will provide an overview of some of these, and present some demonstrations of FP design in practice.
download for better quality - Learn how to use an Applicative Functor to handle multiple independent effectful values through the work of Sergei Winitzki, Runar Bjarnason, Paul Chiusano, Debasish Ghosh and Adelbert Chang
Functions in Scala allow dividing programs into smaller, manageable pieces that perform specific tasks. Some key features of functions in Scala include local functions defined inside other functions, first-class functions that can be passed as arguments, partially applied functions, closures that close over variables from outer scopes, and repeated/variable length parameters indicated with an asterisk. Tail recursion makes recursive functions more efficient by ensuring the recursive call is the last operation.
The document summarizes key points from a lecture on Scala programming:
1. Implicits allow defining implicit conversions to resolve type mismatches and fix compiler errors. Monads separate composition timeline from execution and allow computations to carry extra data.
2. The Option type in Scala is equivalent to Haskell's Maybe monad. It provides flatMap and map operations for monadic computations.
3. Scala supports parallel collections for parallelism and futures for composable concurrent programming. Futures are monads that can be operated on and composed asynchronously.
Functions in C allow programmers to package blocks of code that perform tasks. Functions make code reusable and easier to understand by separating code into modular units. A function has a name, list of arguments it takes, and code that is executed when the function is called. Functions can communicate between each other via parameters passed by value or by reference. Parameters passed by value are copied, so changes inside the function don't affect the original variable, while parameters passed by reference allow the function to modify the original variable. Functions can also call themselves recursively.
Function Composition - forward composition versus backward compositionPhilip Schwarz
The document discusses function composition in Scala. It defines forward composition as applying one function f to the result of another function g, written as f andThen g. Backward composition applies functions in the opposite order, first applying g and then f to the result, written as f compose g. Both operations can be implemented as curried functions in Scala, with andThen and compose respectively, that take the functions as arguments and return a function combining their operations.
Introduction to Functional Programming in JavaScripttmont
A presentation I did for work on functional programming. It's meant as an introduction to functional programming, and I implemented the fundamentals of functional programming (Church Numerals, Y-Combinator, etc.) in JavaScript.
The document discusses various Java operators including:
- Assignment operators like = that store values
- Arithmetic operators like +, -, *, /, % for math operations
- Relational operators like >, <, ==, != for comparisons
- Logical operators like &&, ||, ! for boolean logic
- Bitwise operators like &, |, ^, ~ for bit manipulation
- Shift operators like <<, >>, >>> for shifting bits left or right
Examples are provided to demonstrate the usage of each operator type.
The document discusses different types of storage classes in C++ that determine the lifetime and scope of variables:
1. Local variables are defined inside functions and have scope limited to that function. They are destroyed when the function exits.
2. Global variables are defined outside all functions and have scope in the entire program. They are destroyed when the program ends.
3. Static local variables are local variables that retain their value between function calls. Register variables are local variables stored in processor registers for faster access.
4. Thread local storage allows defining variables that are local to each thread and retain their values similar to static variables. The document provides examples to illustrate local, global, and static variables.
The document discusses functions in C++. It defines functions as modules that can be called to perform tasks and structure programs. Functions may take arguments as input and return values. Well-defined functions have a prototype specifying argument and return types. The document provides examples of built-in functions like sqrt() as well as user-defined functions. It discusses function syntax, calling and defining functions, and variable scope within and outside of functions.
Namespace defines a scope for identifiers used in a program. Reference variables provide an alias for previously defined variables, and their main purpose is passing arguments to functions. C++ defines new and delete operators for allocating and freeing memory. The main() cannot directly access private data members; they must use member functions. A private member function can only be called by another member function of its class. A static member function can be called using the class name as class-name::function-name.
This document provides an overview of a lecture on functional programming in Scala. It covers the following topics:
1. A recap of functional programming principles like functions as first-class values and no side effects.
2. An introduction to the Haskell programming language including its syntax for defining functions.
3. How functions are defined in Scala and how they are objects at runtime.
4. Examples of defining the factorial function recursively in Haskell and Scala, and making it tail recursive.
5. Concepts of first-class functions, currying, partial application, and an example of implementing looping in Scala using these techniques.
This document discusses different types of functions in C++, including user-defined functions, library functions, function parameters, return values, function prototypes, and function overloading. It provides examples to illustrate key concepts like defining functions with different parameters and return types, passing arguments to functions, and returning values from functions. Storage classes like local, global, static local and register variables are also briefly covered. The document is an introduction to functions in C++ programming.
Operators In Java Part - 8
Like My Page:
www.facebook.com/pakcoders
What is Java? Part - 1
https://www.slideshare.net/MuhammadAtif231/what-is-java-part-1
History Of Java Part - 2
https://www.slideshare.net/MuhammadAtif231/history-of-java-part-2
Features Of Java Part - 3
https://www.slideshare.net/MuhammadAtif231/history-of-java-part-2
C++ Vs Java Part - 4
https://www.slideshare.net/MuhammadAtif231/c-vs-java-part-4
First part of this presentation explains basics and advantages of using functional programming approaches with lambda calculus.
Second part of this presentation explains how can we use lambda calculus in C# 3.0
Work common problems out via a functional approach. Think in terms of functions, be lazy, use pipelines and handle concurrency with immutable data borrowing concepts from Haskell/Scala/Erlang. All of this in Python.
This document provides an overview of key Python concepts including operators and expressions, data types, variables, functions, program flow, and input/output. It discusses operators like +, -, *, / and comparison operators. It explains that Python has different data types like integers, floats, booleans and strings. Variables are used to store and reference data. Functions allow for code reuse and modularization. Control structures like if statements allow programs to make decisions based on conditional logic.
(video of these slides available here http://fsharpforfunandprofit.com/fppatterns/)
In object-oriented development, we are all familiar with design patterns such as the Strategy pattern and Decorator pattern, and design principles such as SOLID.
The functional programming community has design patterns and principles as well.
This talk will provide an overview of some of these, and present some demonstrations of FP design in practice.
download for better quality - Learn how to use an Applicative Functor to handle multiple independent effectful values through the work of Sergei Winitzki, Runar Bjarnason, Paul Chiusano, Debasish Ghosh and Adelbert Chang
Functions in Scala allow dividing programs into smaller, manageable pieces that perform specific tasks. Some key features of functions in Scala include local functions defined inside other functions, first-class functions that can be passed as arguments, partially applied functions, closures that close over variables from outer scopes, and repeated/variable length parameters indicated with an asterisk. Tail recursion makes recursive functions more efficient by ensuring the recursive call is the last operation.
The document summarizes key points from a lecture on Scala programming:
1. Implicits allow defining implicit conversions to resolve type mismatches and fix compiler errors. Monads separate composition timeline from execution and allow computations to carry extra data.
2. The Option type in Scala is equivalent to Haskell's Maybe monad. It provides flatMap and map operations for monadic computations.
3. Scala supports parallel collections for parallelism and futures for composable concurrent programming. Futures are monads that can be operated on and composed asynchronously.
Functions in C allow programmers to package blocks of code that perform tasks. Functions make code reusable and easier to understand by separating code into modular units. A function has a name, list of arguments it takes, and code that is executed when the function is called. Functions can communicate between each other via parameters passed by value or by reference. Parameters passed by value are copied, so changes inside the function don't affect the original variable, while parameters passed by reference allow the function to modify the original variable. Functions can also call themselves recursively.
Function Composition - forward composition versus backward compositionPhilip Schwarz
The document discusses function composition in Scala. It defines forward composition as applying one function f to the result of another function g, written as f andThen g. Backward composition applies functions in the opposite order, first applying g and then f to the result, written as f compose g. Both operations can be implemented as curried functions in Scala, with andThen and compose respectively, that take the functions as arguments and return a function combining their operations.
Introduction to Functional Programming in JavaScripttmont
A presentation I did for work on functional programming. It's meant as an introduction to functional programming, and I implemented the fundamentals of functional programming (Church Numerals, Y-Combinator, etc.) in JavaScript.
The document discusses various Java operators including:
- Assignment operators like = that store values
- Arithmetic operators like +, -, *, /, % for math operations
- Relational operators like >, <, ==, != for comparisons
- Logical operators like &&, ||, ! for boolean logic
- Bitwise operators like &, |, ^, ~ for bit manipulation
- Shift operators like <<, >>, >>> for shifting bits left or right
Examples are provided to demonstrate the usage of each operator type.
The document discusses different types of storage classes in C++ that determine the lifetime and scope of variables:
1. Local variables are defined inside functions and have scope limited to that function. They are destroyed when the function exits.
2. Global variables are defined outside all functions and have scope in the entire program. They are destroyed when the program ends.
3. Static local variables are local variables that retain their value between function calls. Register variables are local variables stored in processor registers for faster access.
4. Thread local storage allows defining variables that are local to each thread and retain their values similar to static variables. The document provides examples to illustrate local, global, and static variables.
The document discusses functions in C++. It defines functions as modules that can be called to perform tasks and structure programs. Functions may take arguments as input and return values. Well-defined functions have a prototype specifying argument and return types. The document provides examples of built-in functions like sqrt() as well as user-defined functions. It discusses function syntax, calling and defining functions, and variable scope within and outside of functions.
Namespace defines a scope for identifiers used in a program. Reference variables provide an alias for previously defined variables, and their main purpose is passing arguments to functions. C++ defines new and delete operators for allocating and freeing memory. The main() cannot directly access private data members; they must use member functions. A private member function can only be called by another member function of its class. A static member function can be called using the class name as class-name::function-name.
This document provides an overview of a lecture on functional programming in Scala. It covers the following topics:
1. A recap of functional programming principles like functions as first-class values and no side effects.
2. An introduction to the Haskell programming language including its syntax for defining functions.
3. How functions are defined in Scala and how they are objects at runtime.
4. Examples of defining the factorial function recursively in Haskell and Scala, and making it tail recursive.
5. Concepts of first-class functions, currying, partial application, and an example of implementing looping in Scala using these techniques.
This document discusses different types of functions in C++, including user-defined functions, library functions, function parameters, return values, function prototypes, and function overloading. It provides examples to illustrate key concepts like defining functions with different parameters and return types, passing arguments to functions, and returning values from functions. Storage classes like local, global, static local and register variables are also briefly covered. The document is an introduction to functions in C++ programming.
Operators In Java Part - 8
Like My Page:
www.facebook.com/pakcoders
What is Java? Part - 1
https://www.slideshare.net/MuhammadAtif231/what-is-java-part-1
History Of Java Part - 2
https://www.slideshare.net/MuhammadAtif231/history-of-java-part-2
Features Of Java Part - 3
https://www.slideshare.net/MuhammadAtif231/history-of-java-part-2
C++ Vs Java Part - 4
https://www.slideshare.net/MuhammadAtif231/c-vs-java-part-4
First part of this presentation explains basics and advantages of using functional programming approaches with lambda calculus.
Second part of this presentation explains how can we use lambda calculus in C# 3.0
Work common problems out via a functional approach. Think in terms of functions, be lazy, use pipelines and handle concurrency with immutable data borrowing concepts from Haskell/Scala/Erlang. All of this in Python.
This document provides an overview of key Python concepts including operators and expressions, data types, variables, functions, program flow, and input/output. It discusses operators like +, -, *, / and comparison operators. It explains that Python has different data types like integers, floats, booleans and strings. Variables are used to store and reference data. Functions allow for code reuse and modularization. Control structures like if statements allow programs to make decisions based on conditional logic.
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2Philip Schwarz
(download for perfect quality) See aggregation functions defined inductively and implemented using recursion.
Learn how in many cases, tail-recursion and the accumulator trick can be used to avoid stack-overflow errors.
Watch as general aggregation is implemented and see duality theorems capturing the relationship between left folds and right folds.
Through the work of Sergei Winitzki and Richard Bird.
Please I want a detailed complete answers for each part.Then make.pdfsiennatimbok52331
Please I want a detailed complete answers for each part.Then make sure you provide clear
picture(s) of soultions that I can read. Try making all numbers and letters clrearly readable easy
to recognize. You also can type it which I prefer so I can copy all later, paste them in Microsoft
Word to enlarge & edit if needed. Thanks for all :) 1. Sort the record 9, 34,17,6, 15, 3:8 by using
the following sorting techniques, respectively, 1) QuickSort with a good call for the first pivot
value 2) MergeSort 3) HeapSort (including the details for building 1st Heap, and all 6 heaps) 4)
Binsort (Choose Bins as: 0-9; 10-19, 20-29, 30-39) 5) Radix sort The details of each sorting step
should be ncluded The details of each sorting step should be included
Solution
QuickSort:
QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and partitions the
given array around the picked pivot. There are many different versions of quickSort that pick
pivot in different ways.
The key process in quickSort is partition(). Target of partitions is, given an array and an element
x of array as pivot, put x at its correct position in sorted array and put all smaller elements
(smaller than x) before x, and put all greater elements (greater than x) after x. All this should be
done in linear time
elements:
9 34 17 6 15 38
9 34 17 6 15 38
9 34 17 6 15 38
9 34 17 6 15 38
9 34 17 6 15 38
9 34 17 6 15 38
9 6 17 34 15 38
swapping 15 and 34
15 is choosing pivot
compare with i-1 value
Program
def quickSort(alist):
quickSortHelper(alist,0,len(alist)-1)
def quickSortHelper(alist,first,last):
if first= pivotvalue and rightmark >= leftmark:
rightmark = rightmark -1
if rightmark < leftmark:
done = True
else:
temp = alist[leftmark]
alist[leftmark] = alist[rightmark]
alist[rightmark] = temp
temp = alist[first]
alist[first] = alist[rightmark]
alist[rightmark] = temp
return rightmark
alist = [9,34,17,6,15,8]
quickSort(alist)
print(alist)
Mergesort:
MergeSort is a Divide and Conquer algorithm. It divides input array in two halves, calls itself for
the two halves and then merges the two sorted halves. The merge() function is used for merging
two halves. The merge(arr, l, m, r) is key process that assumes that arr[l..m] and arr[m+1..r] are
sorted and merges the two sorted sub-arrays into one. See following C implementation for
details.
9 34 17 6 15 38
divide two parts
9 34 17 6 15 38
divide separate parts
9 34 17 6 15 38
compare two elements in each section
9 34 17 6 15 38
compare section to section
9 17 34 6 15 38
compare two section
6 9 15 17 34 38
Merges two subarrays of arr[].
# First subarray is arr[l..m]
# Second subarray is arr[m+1..r]
def merge(arr, l, m, r):
n1 = m - l + 1
n2 = r- m
# create temp arrays
L = [0] * (n1)
R = [0] * (n2)
# Copy data to temp arrays L[] and R[]
for i in range(0 , n1):
L[i] = arr[l + i]
for j in range(0 , n2):
R[j] = arr[m + 1 + j]
# Merge the temp arrays back into arr[l..r]
i = 0 # Initial index of first subarray
j = 0 # Initial index of second.
This document discusses loops in R and when to use them versus vectorization. It provides examples of for, while, and repeat loops in R. The key points are:
- Loops allow repeating operations but can be inefficient; vectorization is preferred when possible.
- For loops execute a fixed number of times based on an index or counter. Nested for loops allow manipulating multi-dimensional arrays.
- While and repeat loops execute until a condition is met, but repeat ensures at least one iteration.
- Break and next statements allow interrupting loop iterations early.
This document discusses monads in functional programming. It provides examples of optionals, arrays, and functions in Swift that exhibit monadic properties. It then defines monads more formally and describes some common monad types like the writer, reader, and IO monads. It shows how monads allow encapsulating effects like logging or environment variables while preserving referential transparency. The document concludes by discussing potential applications of monads to mobile apps.
Some key features of Scala include:
1. It allows blending of functional programming and object-oriented programming for more concise and powerful code.
2. The static type system allows for type safety while maintaining expressiveness through type inference, implicits, and other features.
3. Scala code interoperates seamlessly with existing Java code and libraries due to its compatibility with the JVM.
i. The linear convolution of two sequences was calculated using the conv command in MATLAB. The input sequences, individual sequences, and convolved output were plotted.
ii. Linear convolution was also calculated using the DFT and IDFT. The sequences were padded with zeros and transformed to the frequency domain using FFT. The transformed sequences were multiplied and inverse transformed using IFFT to obtain the circular convolution result.
iii. The circular convolution result using DFT/IDFT was the same as the linear convolution using the conv command, demonstrating the equivalence between linear and circular convolution in the frequency domain.
This lab manual covers MATLAB and digital signal processing concepts. It includes:
1) An introduction to MATLAB including basic commands, functions, vectors, matrices and operations.
2) Digital signal processing concepts like sampling, discrete time signals, linear convolution using the conv command are explained.
3) Experiments are included to verify the sampling theorem and study linear convolution of sequences.
Scala is a multi-paradigm programming language that blends object-oriented and functional programming. It is designed to express common programming patterns in a concise, elegant, and type-safe way. Scala runs on the Java Virtual Machine and interoperates seamlessly with Java, but also integrates concepts from languages such as Haskell, ML and Ruby. Some key features of Scala include support for functional programming, a static type system with type inference, pattern matching, actors and immutable data structures.
Principles of functional progrmming in scalaehsoon
a short outline on necessity of functional programming and principles of functional programming in Scala.
In the article some keyword are used but not explained (to keep the article short and simple), the interested reader can look them up in internet.
This document provides an overview of functional programming in Scala. It begins with an introduction to functional programming basics like purity and referential transparency. It then covers functional data structures in Scala, including immutable lists. The document outlines topics on handling errors without exceptions, strict vs non-strict functions, purely functional state, and common FP structures like monoids and monads. Exercises are provided at the end to implement functions like tail, dropWhile, and foldLeft/foldRight on immutable lists.
The Functional Programming Triad of Folding, Scanning and Iteration - a first...Philip Schwarz
This slide deck can work both as an aide mémoire (memory jogger), or as a first (not completely trivial) example of using left folds, left scans and iteration, to implement mathematical induction.
Errata: on almost half of the slides there is some minor typo or imperfection or in some cases a minor error and in one case, an omission. See a later version for corrections and some improvements.
(for best quality images, either download or view here: https://philipschwarz.dev/fpilluminated/?page_id=455)
Scala code for latest version: https://github.com/philipschwarz/fp-fold-scan-iterate-triad-a-first-example-scala
This document provides a brief introduction to the Lisp programming language. It discusses Lisp's history from its origins in 1958 to modern implementations like Common Lisp and Scheme. It also covers Lisp's support for functional, imperative, and object-oriented paradigms. A key feature of Lisp is its use of s-expressions as both code and data, which enables powerful macros to transform and generate code at compile time.
This document provides an introduction and overview of key Python concepts including:
1. Operators and expressions, data types, variables, functions, program flow, input/output, and iteration are introduced.
2. Key Python constructs like if/else conditional statements, while loops, functions, and getting input from the user are demonstrated through examples.
3. Best practices for writing clear, well-structured Python code are discussed, including using parameters in functions, returning values, avoiding hard-coded values, and properly indenting code blocks.
This document provides an outline and overview of key concepts in Python including operators and expressions, data types, variables, functions, program flow, user input, and iteration. It introduces Python syntax, built-in data types like integers, floats, booleans and strings. It describes operators, variables, functions, conditional statements like if/else, and repetition with loops. Examples are provided to demonstrate concepts like arithmetic expressions, type conversion, scope of variables, parameter passing in functions, and handling errors from user input.
Slides for Lecture 1 of the course: Introduction to Programming with Python offered at ICCBS.
It covers the following topics:
1.) Variables, Statements and Expressions
2.) Functions
3.) Flow Control
The document discusses Python's built-in functions for functional programming: map(), filter(), reduce(), and lambda. It provides examples of using each function to transform sequences. Map applies a function to each item in a sequence. Filter filters items based on a function that tests each item. Reduce combines items via a function to produce a single value. These functions allow functional-style programming in Python.
This document provides an outline and overview of key Python concepts including operators, data types, variables, functions, and program flow. It introduces Python as an interpreted programming language with a strict syntax. Operators like +, -, *, / perform actions on operands to produce new values. Data types include integers, floats, booleans and strings. Variables are used to store and reference data. Functions allow for code reuse and abstraction by defining reusable blocks of code. Program flow can be controlled using conditional statements like if/else.
Similar to How to start functional programming (in Scala): Day1 (20)
This document discusses how to work with implicits in Scala. It provides examples of implicit parameters and conversions. It explains that implicits can be difficult because what happens is not explicit, the implicit scope is complicated, and implicits are often designed to be derived. It provides tips for understanding implicits, such as finding working examples, learning common ways to include implicits in scope, and knowing how to modify existing implicit values.
Scala and Akka work well for building resilient and concurrent Android applications like VoIP systems. The actor model in Akka helps encapsulate stateful components and handle errors gracefully. While some challenges exist like dex method limits and Proguard configuration, Scala has been successfully used in large Android apps and provides benefits like a powerful language and ecosystem compared to alternatives like Kotlin.
Measures in SQL (SIGMOD 2024, Santiago, Chile)Julian Hyde
SQL has attained widespread adoption, but Business Intelligence tools still use their own higher level languages based upon a multidimensional paradigm. Composable calculations are what is missing from SQL, and we propose a new kind of column, called a measure, that attaches a calculation to a table. Like regular tables, tables with measures are composable and closed when used in queries.
SQL-with-measures has the power, conciseness and reusability of multidimensional languages but retains SQL semantics. Measure invocations can be expanded in place to simple, clear SQL.
To define the evaluation semantics for measures, we introduce context-sensitive expressions (a way to evaluate multidimensional expressions that is consistent with existing SQL semantics), a concept called evaluation context, and several operations for setting and modifying the evaluation context.
A talk at SIGMOD, June 9–15, 2024, Santiago, Chile
Authors: Julian Hyde (Google) and John Fremlin (Google)
https://doi.org/10.1145/3626246.3653374
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfVALiNTRY360
Salesforce Healthcare CRM, implemented by VALiNTRY360, revolutionizes patient management by enhancing patient engagement, streamlining administrative processes, and improving care coordination. Its advanced analytics, robust security, and seamless integration with telehealth services ensure that healthcare providers can deliver personalized, efficient, and secure patient care. By automating routine tasks and providing actionable insights, Salesforce Healthcare CRM enables healthcare providers to focus on delivering high-quality care, leading to better patient outcomes and higher satisfaction. VALiNTRY360's expertise ensures a tailored solution that meets the unique needs of any healthcare practice, from small clinics to large hospital systems.
For more info visit us https://valintry360.com/solutions/health-life-sciences
What to do when you have a perfect model for your software but you are constrained by an imperfect business model?
This talk explores the challenges of bringing modelling rigour to the business and strategy levels, and talking to your non-technical counterparts in the process.
8 Best Automated Android App Testing Tool and Framework in 2024.pdfkalichargn70th171
Regarding mobile operating systems, two major players dominate our thoughts: Android and iPhone. With Android leading the market, software development companies are focused on delivering apps compatible with this OS. Ensuring an app's functionality across various Android devices, OS versions, and hardware specifications is critical, making Android app testing essential.
Liberarsi dai framework con i Web Component.pptxMassimo Artizzu
In Italian
Presentazione sulle feature e l'utilizzo dei Web Component nell sviluppo di pagine e applicazioni web. Racconto delle ragioni storiche dell'avvento dei Web Component. Evidenziazione dei vantaggi e delle sfide poste, indicazione delle best practices, con particolare accento sulla possibilità di usare web component per facilitare la migrazione delle proprie applicazioni verso nuovi stack tecnologici.
UI5con 2024 - Bring Your Own Design SystemPeter Muessig
How do you combine the OpenUI5/SAPUI5 programming model with a design system that makes its controls available as Web Components? Since OpenUI5/SAPUI5 1.120, the framework supports the integration of any Web Components. This makes it possible, for example, to natively embed own Web Components of your design system which are created with Stencil. The integration embeds the Web Components in a way that they can be used naturally in XMLViews, like with standard UI5 controls, and can be bound with data binding. Learn how you can also make use of the Web Components base class in OpenUI5/SAPUI5 to also integrate your Web Components and get inspired by the solution to generate a custom UI5 library providing the Web Components control wrappers for the native ones.
Project Management: The Role of Project Dashboards.pdfKarya Keeper
Project management is a crucial aspect of any organization, ensuring that projects are completed efficiently and effectively. One of the key tools used in project management is the project dashboard, which provides a comprehensive view of project progress and performance. In this article, we will explore the role of project dashboards in project management, highlighting their key features and benefits.
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesQuickdice ERP
Explore the seamless transition to e-invoicing with this comprehensive guide tailored for Saudi Arabian businesses. Navigate the process effortlessly with step-by-step instructions designed to streamline implementation and enhance efficiency.
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.
13. What is a function?What is a function?
A function is a computation to transform inputs into outputs.
It's an instance of FunctionNtraits in Scala.
FunctionNmeans a function type which takes N arguments
(from 0 to 22).
Function0[T], Function1[T1,T2], ... , Function22[T1,...,T23]
Function1Function1
Int=Intis a type alias to Function1[Int,Int].
scala val double = (i:Int) = i * 2
double: Int = Int = function1
14. Function1 is composable.Function1 is composable.
Function1has andThenand composemethod for function
compositions.
scala val quadraple = double compose double
quadraple: Int = Int = function1
scala quadraple(3)
res0: Int = 12
15. Function2 to 22 don't have thoseFunction2 to 22 don't have those
methods, but...methods, but...
16. Function2 to 22 can be curried.Function2 to 22 can be curried.
Curryingmeans converting a multiple argument funtion to
Function1.
17. Currying Function2Currying Function2
Function2[Int,String,Int]is curriedto
Function1[Int,Function1[String,Int]]
scala val combine = (left:Int, right:Int) = left + right
combine: (Int, Int) = Int = function2
scala combine.curried
res0: Int = (Int = Int) = function1
18. Function2 to 22 can be composed viaFunction2 to 22 can be composed via
currying.currying.
Thus Function1- Function22are composable.
scala double andThen combine.curried
res0: Int = (Int = Int) = function1
19. FP fundamentalsFP fundamentals
As we see, functions can take another function as an
agrument or a return value.
This is to say a function is a rst class citizen.
Those functions are called higher order functions.
Above two are fundamentals in FP.
21. Di erence from functionsDi erence from functions
Method is de ned by def keyword.
Methods can be expanded to FunctionNby _. (eta-expansion)
scala def double(i:Int):Int = i * 2
double: (i: Int)Int
scala double _
res0: Int = Int = function1
22. Methods can take type parameters or an implicit parameter
list, while functions cannot.
23. Methods with type parameterMethods with type parameter
Seq[T] has a method map[U]which modi es Ttyped elements
into Utyped elements.
def map[U](f: T = U): Seq[U]
scala Seq(1,2,3).map(_ + 1)
res0: Seq[Int] = List(2,3,4)
24. Combine all together.Combine all together.
Now we know function composition basics!
scala val apCurried = combine.curried
apCurried: Int = (Int = Int) = function1
// (X + 3) * 2
scala val plus3Double = apCurried(3) andThen double
plus3Double: Int = Int = function1
scala seq = Seq(1,2,3).map(plus3Double)
seq: Seq[Int] = Seq(8,10,12)
26. Watch out side e ectsWatch out side e ects
Changing any state.
Depending on mutable state which may change.
Standard ouput
File I/O
Throwing exceptions.
All above side effects may change functions behaviour
depends on state.
27. What isWhat is resultresult??
var counter = 0
val next = (nth: Int) = {
counter += nth
counter
}
scala next(1)
res0: Int = 1
scala val result = (next andThen next andThen next)(3)
28. You have to care the order of execution and each state, even
if you compose!
It's sometimes hard to predict how impure functions behave.
scala val result = (next andThen next andThen next)(3)
result: Int = 16
29. localize side-e ectslocalize side-e ects
All side effects cannot be removed from your program.
The key is to localize and seperate side effects from other
functions.
30. Referential transparencyReferential transparency
Excluding side-effects, expressions can be replaced with its
evaluation with keeping the meaning of program.
It is called referentially transparent
Referential transparent functions are called pure functions.
32. RethinkRethink combinecombinefunctionfunction
We de ned combinefunction as a binary operation of Int.
It's amazingly useful for fold-like operation.
scala val combine = (left:Int, right:Int) = left + right
combine: (Int, Int) = Int = function2
33. foldLeftfoldLeft
Here is the foldLeftsignature of Seq[A].
This foldLefttakes two arguments - one is a default value,
and another is a binary operation of Int.
def foldLeft[B](z: B)(op: (B, A) ⇒ B): B
34. It folds the sequence from left to right. Thus:
means
(((0 + 1) + 2) + 3)
Seq(1,2,3).foldLeft(0)((x: Int, y:Int) = x + y)
36. combiningcombining Option[Int]Option[Int]scala val combineOptions = (left:Option[Int], right:Option[Int
(left , right) match{
case (None, None) = None
case (Some(l), None) = Some(l)
case (None, Some(r)) = Some(r)
case (Some(l), Some(r)) = Some(l + r)
}
combineOptions: (Option[Int], Option[Int]) = Option[Int] = fun
37. Okay then, how about Seq[Option[String]]?
scala Seq(Some(1),None,Some(3)).foldLeft(None)(combineOptions)
res0: Option[Int] = Some(4)
38. Do we have to de ne combineOptionXXXfor each Option[T]?
39. Abstract from functions.Abstract from functions.
We see the following operations are required for the element
type of Seqand its foldLeftoperation.
returning default value
binary operation
40. Let's abstract these two and make a certain type for them.
We call the type Monoid.
42. De neDe ne MonoidMonoidofof IntIntandand StringString
In this context, implicitis the keyword to pass a value as an
argument implicitly.
implicit val intMonoid: Monoid[Int] = new Monoid[Int] {
val empty: Int = 0
def combine(left: Int, right: Int): Int = left + right
}
43. implicit val stringMonoid: Monoid[String] = new Monoid[String] {
val empty: String =
def combine(left: String, right: String): String = left + righ
}
44. Induce Monoid of Option[T]Induce Monoid of Option[T]
Now Monoid[Option[T]]instance can be induced from
Monoid[T]instance.
45. (Disclaimer: for simplicity, above induction function is de ned as T
type has to be Monoid, instead of Semigroup. )
implicit def optionMonoid[T](implicit M:Monoid[T]): Monoid[Optio
val empty: Option[T] = None
def combine(left:Option[T], right:Option[T]) =
(left , right) match{
case (None, None) = None
case (Some(l), None) = Some(l)
case (None, Some(r)) = Some(r)
case (Some(l), Some(r)) = Some(M.combine(l, r))
}
}
46. Compose Monoids for tupleCompose Monoids for tuple
You can also compose Monoid instances.
implicit def tupleMonoid[S,T](implicit MS:Monoid[S], MT:Monoid[T
new Monoid[(S,T)]{
val empty: (S,T) = (MS.empty, MT.empty)
def combine(left:(S,T), right:(S,T)) =
(MS.combine(left._1, right._1), MT.combine(left._2, righ
}
47. De neDe ne foldLeftfoldLeftmethod to usemethod to use
MonoidMonoiddef foldLeft[T](seq: Seq[T])(implicit M:Monoid[T]): T = seq.fold
50. Cooler stu ofCooler stu of MonoidMonoid
Let's de ne a new fold operation like foldMapusing Monoid.
51. Now you can map values and fold them with traversing a
sequence just once!
def foldMap[T,U](s: Seq[T])(f: T = U)(implicit M:Monoid[U]) =
s.foldLeft(M.empty){case (l, r) = M.combine(l, f(r))}
scala foldMap(Seq(1,2,3))(_.toString)
res0: String = 123
52. RecapRecap MonoidMonoid- it's a typeclass.- it's a typeclass.
Monoid[T]is a type for a binary operation and a default value
against Ttype.
53. By de ning Monoid[T]instance against Ttype, new
behaviours are added into Ttype.
54. Monoidis so called typeclass and above description is the
bene t of typeclass.
55. What is typeclass?What is typeclass?
typeclass comes from Functional Language Haskell to
contrain a type parameter and admit new functions to its
type.
56. It means adding new behaviours into exisiting types without
changing their codebase!
57. Thus you can add new behaviours into even Stringtype
which souce codes cannot be modi ed or extended.
59. Typeclasses out of the boxTypeclasses out of the box
Scala standard library de nes several typeclasses.
Ordering[T]typeclass is to de ne natural ordering of Ttype.
60. sortedmethod in Seq[T]use Ordering[T]typeclass
instances otherwise it fails to compile.
def sorted[B : A](implicit ord: math.Ordering[B]): List[A]
scala Seq(3,1,2).sorted
res3: Seq[Int] = List(1, 2, 3)
61. Typeclass works well with OOPTypeclass works well with OOP
Typeclass is not a concept just for Functional Programming.