Big picture of category theory in scala with deep dive into contravariant and...Piotr Paradziński
A big picture of category theory in Scala - starting from regular functors with additional structure (Apply, Applicative, Monad) to Comonads. Usually, we think about structures like Monoids in a monoidal category with particular tensor. In here I analyze just signatures of different abstractions.
Exploration of Contravariant functors as a way to model computation "backward" or abstract over input with the ability to prepend operation. Examples for predicates, sorting, show and function input (or any other function parameter except the last one).
Profunctors as abstraction unifying Functors and Contravariant functors to model both input and output. Example for Profunctor - function with one argument.
Relation to Bifunctors, Kan extensions, Adjunctions, and Free constructions.
Download for better quality.
Monads do not Compose. Not in a generic way - There is no general way of composing monads.
A comment from Rúnar Bjarnason, coauthor of FP in Scala: "They do compose in a different generic way. For any two monads F and G we can take the coproduct which is roughly Free of Either F or G (up to normalization)".
Another comment from Sergei Winitzki (which caused me to upload https://www.slideshare.net/pjschwarz/addendum-to-monads-do-not-compose): "It is a mistake to think that a traversable monad can be composed with another monad. It is true that, given `Traversable`, you can implement the monad's methods (pure and flatMap) for the composition with another monad (as in your slides 21 to 26), but this is a deceptive appearance. The laws of the `Traversable` typeclass are far insufficient to guarantee the laws of the resulting composed monad. The only traversable monads that work correctly are Option, Either, and Writer. It is true that you can implement the type signature of the `swap` function for any `Traversable` monad. However, the `swap` function for monads needs to satisfy very different and stronger laws than the `sequence` function from the `Traversable` type class. I'll have to look at the "Book of Monads"; but, if my memory serves, the FPiS book does not derive any of these laws." See https://www.linkedin.com/feed/update/urn:li:groupPost:41001-6523141414614814720?commentUrn=urn%3Ali%3Acomment%3A%28groupPost%3A41001-6523141414614814720%2C6532108273053761536%29
download for better quality - Learn about the sequence and traverse functions through the work of Runar Bjarnason and Paul Chiusano, authors of Functional Programming in Scala https://www.manning.com/books/functional-programming-in-scala, and Sam Halliday, author of "Functional Programming for Mortals with Scalaz" https://leanpub.com/fpmortals
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsJohn De Goes
Quark is a new Scala DSL for data processing and analytics that runs on top of the Quasar Analytics compiler. Quark is adept at processing semi-structured data and compiles query plans to operations that run entirely inside a target data source. In this presentation, John A. De Goes provides an overview of the open source library, showing several use cases in data processing and analytics. John also demonstrates a powerful technique that every developer can use to create their own purely-functional, type-safe DSLs in the Scala programming language.
Monoids - Part 2 - with examples using Scalaz and CatsPhilip Schwarz
The document discusses monoids in Scalaz and Cats, specifically for the Option type. It explains that in Scalaz there are three Option monoids (optionFirst, optionLast, optionMonoid) that combine Options in different ways, while Cats only has one Option monoid (optionMonoid) that combines the contents. It also introduces MonoidK, which allows constructing a monoid that behaves like optionFirst by combining Options based on their orElse method. The document provides examples and explanations of how Semigroup, SemigroupK, Monoid, and MonoidK work and differ for types like List, Set, and Option. It also defines a monoid for endofunctions that composes
The document discusses functor composition and the functor laws. It explains that the composition of two functors F and G is itself a functor, where the map operation maps a function f by first applying F's map to lift f into F, and then applying G's map to lift the result into G. This satisfies the functor laws, where the mapping of a composition of functions is the composition of their individual mappings.
Big picture of category theory in scala with deep dive into contravariant and...Piotr Paradziński
A big picture of category theory in Scala - starting from regular functors with additional structure (Apply, Applicative, Monad) to Comonads. Usually, we think about structures like Monoids in a monoidal category with particular tensor. In here I analyze just signatures of different abstractions.
Exploration of Contravariant functors as a way to model computation "backward" or abstract over input with the ability to prepend operation. Examples for predicates, sorting, show and function input (or any other function parameter except the last one).
Profunctors as abstraction unifying Functors and Contravariant functors to model both input and output. Example for Profunctor - function with one argument.
Relation to Bifunctors, Kan extensions, Adjunctions, and Free constructions.
Download for better quality.
Monads do not Compose. Not in a generic way - There is no general way of composing monads.
A comment from Rúnar Bjarnason, coauthor of FP in Scala: "They do compose in a different generic way. For any two monads F and G we can take the coproduct which is roughly Free of Either F or G (up to normalization)".
Another comment from Sergei Winitzki (which caused me to upload https://www.slideshare.net/pjschwarz/addendum-to-monads-do-not-compose): "It is a mistake to think that a traversable monad can be composed with another monad. It is true that, given `Traversable`, you can implement the monad's methods (pure and flatMap) for the composition with another monad (as in your slides 21 to 26), but this is a deceptive appearance. The laws of the `Traversable` typeclass are far insufficient to guarantee the laws of the resulting composed monad. The only traversable monads that work correctly are Option, Either, and Writer. It is true that you can implement the type signature of the `swap` function for any `Traversable` monad. However, the `swap` function for monads needs to satisfy very different and stronger laws than the `sequence` function from the `Traversable` type class. I'll have to look at the "Book of Monads"; but, if my memory serves, the FPiS book does not derive any of these laws." See https://www.linkedin.com/feed/update/urn:li:groupPost:41001-6523141414614814720?commentUrn=urn%3Ali%3Acomment%3A%28groupPost%3A41001-6523141414614814720%2C6532108273053761536%29
download for better quality - Learn about the sequence and traverse functions through the work of Runar Bjarnason and Paul Chiusano, authors of Functional Programming in Scala https://www.manning.com/books/functional-programming-in-scala, and Sam Halliday, author of "Functional Programming for Mortals with Scalaz" https://leanpub.com/fpmortals
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsJohn De Goes
Quark is a new Scala DSL for data processing and analytics that runs on top of the Quasar Analytics compiler. Quark is adept at processing semi-structured data and compiles query plans to operations that run entirely inside a target data source. In this presentation, John A. De Goes provides an overview of the open source library, showing several use cases in data processing and analytics. John also demonstrates a powerful technique that every developer can use to create their own purely-functional, type-safe DSLs in the Scala programming language.
Monoids - Part 2 - with examples using Scalaz and CatsPhilip Schwarz
The document discusses monoids in Scalaz and Cats, specifically for the Option type. It explains that in Scalaz there are three Option monoids (optionFirst, optionLast, optionMonoid) that combine Options in different ways, while Cats only has one Option monoid (optionMonoid) that combines the contents. It also introduces MonoidK, which allows constructing a monoid that behaves like optionFirst by combining Options based on their orElse method. The document provides examples and explanations of how Semigroup, SemigroupK, Monoid, and MonoidK work and differ for types like List, Set, and Option. It also defines a monoid for endofunctions that composes
The document discusses functor composition and the functor laws. It explains that the composition of two functors F and G is itself a functor, where the map operation maps a function f by first applying F's map to lift f into F, and then applying G's map to lift the result into G. This satisfies the functor laws, where the mapping of a composition of functions is the composition of their individual mappings.
The Next Great Functional Programming LanguageJohn De Goes
A LambdaConf 2015 talk.
John has no clue what the next great functional programming language will be like, but he's more than happy to hop up on stage and rant against type classes, nominative typing, data, modules, pattern matching, recursion, and, well, basically everything else you associate with functional programming! John will argue that to make radical progress in cheaply building correct software, we need to take one step backward and two steps forward, embracing dependent-typing, total functions, Turing-complete compilers, host languages, and automated proof search. Attend this talk to question your assumptions about functional programming... or just to heckle! Either way, all are welcome.
What's the best way to model modular, composable effects in your purely functional program? In this presentation, I take a look at monad transformers and free monads, discuss their history, and compare how effectively they solve the problem.
A minimal collection of most wanted and widely accepted idioms and coding conventions for C++ development presented with examples and explanations. The lecture targets performance oriented codes so emphasis is on performance-friendly techiques.
Topics covered:
1) Design issues: idioms and best practices
- Resource Aquisition Is Initialization (RAII)
- Ownership semantics and smart pointers
- Header files: dependencies and decoupling
2) Objects Construction/Destruction/Copying
- Designing constructors
- Rule Of Three
- Transactional programming
3) Namespaces
- ADL/Koenig Lookup
4) Static analyzers
Function Programming in Scala.
A lot of my examples here comes from the book
Functional programming in Scala By Paul Chiusano and Rúnar Bjarnason, It is a good book, buy it.
LISP Language, LISP Introduction, List Processing, LISP Syntax, Lisp Comparison Structures, Lisp Applications. Using of LISP language in Artificial Intelligence
For the past few years in the functional Scala community, the standard approach for adding features to an effect type (features like logging, stateful updates, or accessing config) has been Monad Transformers (EItherT, OptionT, WriterT, ReaderT, etc.).
While elegant and proven, monad transformers were imported directly from Haskell, and in Scala, they have poor ergonomics and poor performance. Using tagless-final on transformers can eliminate some of the boilerplate, but cannot improve performance, and tagless-final makes it insanely hard to locally introduce and eliminate features.
In this presentation, John will introduce an alternate approach he coined ‘effect rotation’, which shares most of the power of monad transformers, but with better ergonomics and no loss of performance. You will see how to use the ZIO library that John created to composably add different features into the ZIO effect type, to solve the same problems as monad transformers, but in a way that feels natural and idiomatic for Scala.
The document discusses Arrow, a generalization of functions in Scala. Arrows can represent computations with multiple inputs through tuples. The document defines Arrow traits and shows examples of Arrow combinators like first, second, split, and combine. It also compares Arrows to Applicatives and Monads. Arrows provide building blocks for functional reactive programming but have clumsy syntax. The document further discusses Arrow extensions like ArrowChoice and ArrowLoop, which enables feedback loops through lazy evaluation. It concludes with Comonads, which consume context, and MonadFix, which enables stackless recursion.
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.
download for better quality - Learn about the sequence and traverse functions
through the work of Runar Bjarnason and Paul Chiusano, authors of Functional Programming in Scala https://www.manning.com/books/functional-programming-in-scala, and others (Martin Odersky, Derek Wyatt, Adelbert Chang)
What would be a good answer to the question of what functors are? To help formulating a reasonably well rounded answer, I have made some slides capturing what I considere particularly useful aspects of the following sources’ exposition of the concept of Functor:
* Bartosz Milewski’s Scala eXchange 2017 Keynote, The Maths Behind Types
*Paul Chiusano and Runar Bjarnason’s book, Functional Programming in Scala
* Debasish Ghosh’s book - Functional and Reactive Domain Modeling
* Christopher Allen, and Julie Moronuki's book - Haskell Programming from First Principles
The document discusses Applicative Functors, Monads, Foldables and Traversables in Scala. Some key points:
1. Applicative Functors allow applying functions to values inside data structures in a point-free style, while preserving the structure.
2. Monads are more powerful than Applicative Functors as they can flatten nested structures and change behavior through chaining of functions.
3. Foldables allow aggregating values inside a data structure using a Monoid. Traversables generalize Foldables by keeping the structure intact using an Applicative instead of a Monoid.
4. Composition of Applicative Functors is possible generically, but composition of
Monoids - Part 1 - with examples using Scalaz and CatsPhilip Schwarz
A monoid is an algebraic structure consisting of a set and a binary operation that is associative and has an identity element. Some key properties of monoids include:
1) A monoid consists of a type A, a binary operation op that combines two values of type A, and a zero value that acts as an identity.
2) The binary operation must be associative, meaning op(op(x,y),z) = op(x,op(y,z)).
3) The zero value must satisfy the identity laws: op(x, zero) = x and op(zero, x) = x.
4) Common examples of monoids include string concatenation
Introduction to Lisp. A survey of lisp's history, current incarnations and advanced features such as list comprehensions, macros and domain-specific-language [DSL] support.
This document provides a summary of C# and .NET core concepts including:
1. Data types and their sizes in C#.
2. How to declare and perform operations on arrays such as sorting, clearing, and copying elements.
3. Methods for performing common string operations like comparison, indexing, replacing, and splitting.
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Philip Schwarz
Quicksort - a whistle-stop tour of the algorithm in five languages and four paradigms.
Programming Paradigms: Functional, Logic, Imperative, Imperative Functional
Languages: Haskell, Scala, Java, Clojure, Prolog
Download for flawless quality (slides viewed online look a bit grainy and out of focus).
Equivalence of nested flatMaps and chained flatMaps for Kleisli arrow composition.
Some languages, like SML, Haskell, and Scala, have built-in support for pattern matching, which is a generic way of branching based on the structure of data.
While not without its drawbacks, pattern matching can help eliminate a lot of boilerplate, and it's often cited as a reason why functional programming languages are so concise.
In this talk, John A. De Goes talks about the differences between built-in patterns, and so-called first-class patterns (which are "do-it-yourself" patterns implemented using other language features).
Unlike built-in patterns, first-class patterns aren't magical, so you can store them in variables and combine them in lots of interesting ways that aren't always possible with built-in patterns. In addition, almost every programming language can support first-class patterns (albeit with differing levels of effort and type-safety).
During the talk, you'll watch as a mini-pattern matching library is developed, and have the opportunity to follow along and build your own pattern matching library in the language of your choice.
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.
Big picture of category theory in scala with deep dive into contravariant and...Scalac
A big picture of category theory in Scala - starting from regular functors with additional structure (Apply, Applicative, Monad) to Comonads. Usually, we think about structures like Monoids in a monoidal category with particular tensor. In here I analyze just signatures of different abstractions.
Exploration of Contravariant functors as a way to model computation "backward" or abstract over input with the ability to prepend operation. Examples for predicates, sorting, show and function input (or any other function parameter except the last one).
Profunctors as abstraction unifying Functors and Contravariant functors to model both input and output. Example for Profunctor - function with one argument.
Relation to Bifunctors, Kan extensions, Adjunctions, and Free constructions.
Shape Safety in Tensor Programming is Easy for a Theorem Prover -SBTB 2021Peng Cheng
This document discusses the Shapesafe project, which uses dependent types in Scala to enable type-safe linear algebra operations. It aims to push type safety to the extreme by exploring symbolic reasoning and weird operands. The author maintains Shapesafe uses the Curry-Howard isomorphism to translate proofs to functional programs. Moving forward, Shapesafe could benefit from Scala 3's improved type inference and implicit resolution, though some Shapeless features may need to be reimplemented. The end goal is to integrate Shapesafe into machine learning libraries to catch errors at compile-time.
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.
The Next Great Functional Programming LanguageJohn De Goes
A LambdaConf 2015 talk.
John has no clue what the next great functional programming language will be like, but he's more than happy to hop up on stage and rant against type classes, nominative typing, data, modules, pattern matching, recursion, and, well, basically everything else you associate with functional programming! John will argue that to make radical progress in cheaply building correct software, we need to take one step backward and two steps forward, embracing dependent-typing, total functions, Turing-complete compilers, host languages, and automated proof search. Attend this talk to question your assumptions about functional programming... or just to heckle! Either way, all are welcome.
What's the best way to model modular, composable effects in your purely functional program? In this presentation, I take a look at monad transformers and free monads, discuss their history, and compare how effectively they solve the problem.
A minimal collection of most wanted and widely accepted idioms and coding conventions for C++ development presented with examples and explanations. The lecture targets performance oriented codes so emphasis is on performance-friendly techiques.
Topics covered:
1) Design issues: idioms and best practices
- Resource Aquisition Is Initialization (RAII)
- Ownership semantics and smart pointers
- Header files: dependencies and decoupling
2) Objects Construction/Destruction/Copying
- Designing constructors
- Rule Of Three
- Transactional programming
3) Namespaces
- ADL/Koenig Lookup
4) Static analyzers
Function Programming in Scala.
A lot of my examples here comes from the book
Functional programming in Scala By Paul Chiusano and Rúnar Bjarnason, It is a good book, buy it.
LISP Language, LISP Introduction, List Processing, LISP Syntax, Lisp Comparison Structures, Lisp Applications. Using of LISP language in Artificial Intelligence
For the past few years in the functional Scala community, the standard approach for adding features to an effect type (features like logging, stateful updates, or accessing config) has been Monad Transformers (EItherT, OptionT, WriterT, ReaderT, etc.).
While elegant and proven, monad transformers were imported directly from Haskell, and in Scala, they have poor ergonomics and poor performance. Using tagless-final on transformers can eliminate some of the boilerplate, but cannot improve performance, and tagless-final makes it insanely hard to locally introduce and eliminate features.
In this presentation, John will introduce an alternate approach he coined ‘effect rotation’, which shares most of the power of monad transformers, but with better ergonomics and no loss of performance. You will see how to use the ZIO library that John created to composably add different features into the ZIO effect type, to solve the same problems as monad transformers, but in a way that feels natural and idiomatic for Scala.
The document discusses Arrow, a generalization of functions in Scala. Arrows can represent computations with multiple inputs through tuples. The document defines Arrow traits and shows examples of Arrow combinators like first, second, split, and combine. It also compares Arrows to Applicatives and Monads. Arrows provide building blocks for functional reactive programming but have clumsy syntax. The document further discusses Arrow extensions like ArrowChoice and ArrowLoop, which enables feedback loops through lazy evaluation. It concludes with Comonads, which consume context, and MonadFix, which enables stackless recursion.
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.
download for better quality - Learn about the sequence and traverse functions
through the work of Runar Bjarnason and Paul Chiusano, authors of Functional Programming in Scala https://www.manning.com/books/functional-programming-in-scala, and others (Martin Odersky, Derek Wyatt, Adelbert Chang)
What would be a good answer to the question of what functors are? To help formulating a reasonably well rounded answer, I have made some slides capturing what I considere particularly useful aspects of the following sources’ exposition of the concept of Functor:
* Bartosz Milewski’s Scala eXchange 2017 Keynote, The Maths Behind Types
*Paul Chiusano and Runar Bjarnason’s book, Functional Programming in Scala
* Debasish Ghosh’s book - Functional and Reactive Domain Modeling
* Christopher Allen, and Julie Moronuki's book - Haskell Programming from First Principles
The document discusses Applicative Functors, Monads, Foldables and Traversables in Scala. Some key points:
1. Applicative Functors allow applying functions to values inside data structures in a point-free style, while preserving the structure.
2. Monads are more powerful than Applicative Functors as they can flatten nested structures and change behavior through chaining of functions.
3. Foldables allow aggregating values inside a data structure using a Monoid. Traversables generalize Foldables by keeping the structure intact using an Applicative instead of a Monoid.
4. Composition of Applicative Functors is possible generically, but composition of
Monoids - Part 1 - with examples using Scalaz and CatsPhilip Schwarz
A monoid is an algebraic structure consisting of a set and a binary operation that is associative and has an identity element. Some key properties of monoids include:
1) A monoid consists of a type A, a binary operation op that combines two values of type A, and a zero value that acts as an identity.
2) The binary operation must be associative, meaning op(op(x,y),z) = op(x,op(y,z)).
3) The zero value must satisfy the identity laws: op(x, zero) = x and op(zero, x) = x.
4) Common examples of monoids include string concatenation
Introduction to Lisp. A survey of lisp's history, current incarnations and advanced features such as list comprehensions, macros and domain-specific-language [DSL] support.
This document provides a summary of C# and .NET core concepts including:
1. Data types and their sizes in C#.
2. How to declare and perform operations on arrays such as sorting, clearing, and copying elements.
3. Methods for performing common string operations like comparison, indexing, replacing, and splitting.
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Philip Schwarz
Quicksort - a whistle-stop tour of the algorithm in five languages and four paradigms.
Programming Paradigms: Functional, Logic, Imperative, Imperative Functional
Languages: Haskell, Scala, Java, Clojure, Prolog
Download for flawless quality (slides viewed online look a bit grainy and out of focus).
Equivalence of nested flatMaps and chained flatMaps for Kleisli arrow composition.
Some languages, like SML, Haskell, and Scala, have built-in support for pattern matching, which is a generic way of branching based on the structure of data.
While not without its drawbacks, pattern matching can help eliminate a lot of boilerplate, and it's often cited as a reason why functional programming languages are so concise.
In this talk, John A. De Goes talks about the differences between built-in patterns, and so-called first-class patterns (which are "do-it-yourself" patterns implemented using other language features).
Unlike built-in patterns, first-class patterns aren't magical, so you can store them in variables and combine them in lots of interesting ways that aren't always possible with built-in patterns. In addition, almost every programming language can support first-class patterns (albeit with differing levels of effort and type-safety).
During the talk, you'll watch as a mini-pattern matching library is developed, and have the opportunity to follow along and build your own pattern matching library in the language of your choice.
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.
Big picture of category theory in scala with deep dive into contravariant and...Scalac
A big picture of category theory in Scala - starting from regular functors with additional structure (Apply, Applicative, Monad) to Comonads. Usually, we think about structures like Monoids in a monoidal category with particular tensor. In here I analyze just signatures of different abstractions.
Exploration of Contravariant functors as a way to model computation "backward" or abstract over input with the ability to prepend operation. Examples for predicates, sorting, show and function input (or any other function parameter except the last one).
Profunctors as abstraction unifying Functors and Contravariant functors to model both input and output. Example for Profunctor - function with one argument.
Relation to Bifunctors, Kan extensions, Adjunctions, and Free constructions.
Shape Safety in Tensor Programming is Easy for a Theorem Prover -SBTB 2021Peng Cheng
This document discusses the Shapesafe project, which uses dependent types in Scala to enable type-safe linear algebra operations. It aims to push type safety to the extreme by exploring symbolic reasoning and weird operands. The author maintains Shapesafe uses the Curry-Howard isomorphism to translate proofs to functional programs. Moving forward, Shapesafe could benefit from Scala 3's improved type inference and implicit resolution, though some Shapeless features may need to be reimplemented. The end goal is to integrate Shapesafe into machine learning libraries to catch errors at compile-time.
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.
This document summarizes key parts of Java 8 including lambda expressions, method references, default methods, streams API improvements, removal of PermGen space, and the new date/time API. It provides code examples and explanations of lambda syntax and functional interfaces. It also discusses advantages of the streams API like lazy evaluation and parallelization. Finally, it briefly outlines the motivation for removing PermGen and standardizing the date/time API in Java 8.
Functional Programming Concepts for Imperative ProgrammersChris
The document discusses functional programming concepts including the origins of the λ-calculus and Lisp. It covers functions as data, lambda expressions, closures, function composition, and higher-order functions. Examples are provided in JavaScript and Scala of implementing functions like fold to operate on lists. While many functional concepts are covered, topics like currying, monads, and lazy evaluation are noted but not discussed in detail.
This document discusses the history and evolution of functional programming in Java, including lambda expressions and streams. It describes how lambda expressions allow passing behaviors as arguments to methods like normal data. This improves API design, opportunities for optimization, and code readability. Streams encourage a lazy, pipelined style and can execute operations in parallel. Functional idioms like immutability and pure functions help enforce correctness and isolation of side effects.
The document discusses a Scala session on functions and higher-order functions. It provides examples of defining functions to calculate the square root of a number, sum values between ranges, and pass functions as parameters. Higher-order functions are introduced as functions that can take other functions as parameters or return functions.
Introduction to Functional Programming with Scalapramode_ce
The document provides an introduction to functional programming with Scala. It outlines the following topics that will be covered: learning Scala syntax and writing simple programs; important functional programming concepts like closures, higher-order functions, purity, lazy evaluation, currying, tail calls, immutability, and type inference; and understanding the functional programming paradigm through Scala. It also provides some background information on Scala and examples of Scala code demonstrating various concepts.
The document provides an overview of the Scala programming language. It begins with an agenda that outlines topics like differences between Java and Scala, Scala data types, variables, classes, functions, closures, exception handling and collections. It then discusses specific aspects of Scala like verbosity reduction compared to Java, functional programming influences, object-oriented features, interoperability with Java and compilation to Java bytecode. Examples are provided to illustrate Scala concepts like functions, classes, recursion, higher-order functions and exception handling. The document aims to explain Scala and reasons for differences from Java.
The document discusses Scala, a programming language designed to be scalable. It can be used for both small and large programs. Scala combines object-oriented and functional programming. It interoperates seamlessly with Java but allows developers to add new constructs like actors through libraries. The Scala community is growing, with industrial adoption starting at companies like Twitter.
This document provides an agenda and overview for a Spark workshop covering Spark basics and streaming. The agenda includes sections on Scala, Spark, Spark SQL, and Spark Streaming. It discusses Scala concepts like vals, vars, defs, classes, objects, and pattern matching. It also covers Spark RDDs, transformations, actions, sources, and the spark-shell. Finally, it briefly introduces Spark concepts like broadcast variables, accumulators, and spark-submit.
The document discusses Java 8 lambda expressions and how they improved Java by allowing for anonymous functions. It provides examples of code before and after Java 8 that demonstrate lambda expressions providing a clearer syntax compared to anonymous inner classes. Specifically, it shows how lambda expressions allowed sorting a list of strings in a more readable way. It also discusses how functions can be treated as data by being passed as parameters or returned from other functions.
What did functional programming ever do for us (software engineers)? An overview of advantages of functional programming, with code examples in Scala. See recorded presentation at https://youtu.be/glDudJ3fqLk
Kotlin Advanced - language reference for Android developers STX Next
StxNext Lightning Talks - Mar 11, 2016
This presentation contains the second talk on Kotlin language we had at STXNext. We try go deeper into language specifics and look at the positive impact new syntax can have on boilerplate removal and readability improvement.
Kotlin really shines in Android development when one looks at “Enum translation”, “Extension functions”, “SAM conversions”, “Infix notation”, “Closures” and “Fluent interfaces” applied to lists. The talk, however, compares language-specifics of Java & Kotlin in terms of “Type Variance”, “Generics” and “IDE tools” as well.
We present real-world example based on Stx-Insider project written in Kotlin which incorporates Dagger 2, Kotterknife, Retrofit2 and is composed of 5+ Activities.
Kotlin advanced - language reference for android developersBartosz Kosarzycki
StxNext Lightning Talks - Mar 11, 2016
Kotlin Advanced - language reference for Android developers
This presentation contains the second talk on Kotlin language we had at STXNext. We try go deeper into language specifics and look at the positive impact new syntax can have on boilerplate removal and readability improvement.
Kotlin really shines in Android development when one looks at “Enum translation”, “Extension functions”, “SAM conversions”, “Infix notation”, “Closures” and “Fluent interfaces” applied to lists. The talk, however, compares language-specifics of Java & Kotlin in terms of “Type Variance”, “Generics” and “IDE tools” as well.
We present real-world example based on Stx-Insider project written in Kotlin which incorporates Dagger 2, Kotterknife, Retrofit2 and is composed of 5+ Activities.
Full agenda
Live templates
Enum translation
Calling extension functions from Kotlin/Java
Constructors with backing fields
Warnings
F-bound polymorphism
Variance (Covariance/Contravariance)
Variance comparison in Kotlin/Java/Scala
Annotation processing - KAPT
SAM conversions
Type equality
Lambda vs Closure
Reified generics
Fluent interfaces
Infix notation
Static extension methods in Kotlin
Generic types
Sealed classes
Dokka - documentation in Kotlin
J2K converter
Real-world example
Reflection
Presentation is accompanied with an example project (StxInsider):
https://github.com/kosiara/stx-insider
Столпы функционального программирования для адептов ООП, Николай МозговойSigma Software
This document provides an overview of functional programming concepts for object-oriented programmers. It discusses the fundamentals of FP including immutability, purity, first-class and higher-order functions, closures, and recursion. It provides examples of these concepts in languages like Lisp, F#, C#, and JavaScript. The document also compares OO and FP concepts and discusses derived FP concepts like partial application, lazy evaluation, and pattern matching.
The document discusses how to rewrite Java code in Scala by taking advantage of Scala's functional programming features like case classes, pattern matching, filters, maps, folds, and generators to make the code more concise and readable. It provides examples of rewriting common Java constructs like filtering lists, mapping over lists, and reducing lists using these Scala features.
Programming Android Application in Scala.Brian Hsu
The document discusses using Scala to develop Android applications. Scala allows satisfying three desires at once: REPL, scripting, and compiling. It supports traits for mixin composition, functional programming, static typing with duck typing. SBT is introduced as a build tool for Scala/Android projects that does not require configuration and supports continuous compilation with an Android plugin. Live demos show installing SBT/SBT-Android and creating a sample Scala/Android project. Some limitations of Scala with Android like accessing static protected Java fields are also mentioned.
Using Query Store in Azure PostgreSQL to Understand Query PerformanceGrant Fritchey
Microsoft has added an excellent new extension in PostgreSQL on their Azure Platform. This session, presented at Posette 2024, covers what Query Store is and the types of information you can get out of it.
SOCRadar's Aviation Industry Q1 Incident Report is out now!
The aviation industry has always been a prime target for cybercriminals due to its critical infrastructure and high stakes. In the first quarter of 2024, the sector faced an alarming surge in cybersecurity threats, revealing its vulnerabilities and the relentless sophistication of cyber attackers.
SOCRadar’s Aviation Industry, Quarterly Incident Report, provides an in-depth analysis of these threats, detected and examined through our extensive monitoring of hacker forums, Telegram channels, and dark web platforms.
Takashi Kobayashi and Hironori Washizaki, "SWEBOK Guide and Future of SE Education," First International Symposium on the Future of Software Engineering (FUSE), June 3-6, 2024, Okinawa, Japan
Odoo ERP software
Odoo ERP software, a leading open-source software for Enterprise Resource Planning (ERP) and business management, has recently launched its latest version, Odoo 17 Community Edition. This update introduces a range of new features and enhancements designed to streamline business operations and support growth.
The Odoo Community serves as a cost-free edition within the Odoo suite of ERP systems. Tailored to accommodate the standard needs of business operations, it provides a robust platform suitable for organisations of different sizes and business sectors. Within the Odoo Community Edition, users can access a variety of essential features and services essential for managing day-to-day tasks efficiently.
This blog presents a detailed overview of the features available within the Odoo 17 Community edition, and the differences between Odoo 17 community and enterprise editions, aiming to equip you with the necessary information to make an informed decision about its suitability for your business.
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.
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppGoogle
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
👉👉 Click Here To Get More Info 👇👇
https://sumonreview.com/ai-fusion-buddy-review
AI Fusion Buddy Review: Key Features
✅Create Stunning AI App Suite Fully Powered By Google's Latest AI technology, Gemini
✅Use Gemini to Build high-converting Converting Sales Video Scripts, ad copies, Trending Articles, blogs, etc.100% unique!
✅Create Ultra-HD graphics with a single keyword or phrase that commands 10x eyeballs!
✅Fully automated AI articles bulk generation!
✅Auto-post or schedule stunning AI content across all your accounts at once—WordPress, Facebook, LinkedIn, Blogger, and more.
✅With one keyword or URL, generate complete websites, landing pages, and more…
✅Automatically create & sell AI content, graphics, websites, landing pages, & all that gets you paid non-stop 24*7.
✅Pre-built High-Converting 100+ website Templates and 2000+ graphic templates logos, banners, and thumbnail images in Trending Niches.
✅Say goodbye to wasting time logging into multiple Chat GPT & AI Apps once & for all!
✅Save over $5000 per year and kick out dependency on third parties completely!
✅Brand New App: Not available anywhere else!
✅ Beginner-friendly!
✅ZERO upfront cost or any extra expenses
✅Risk-Free: 30-Day Money-Back Guarantee!
✅Commercial License included!
See My Other Reviews Article:
(1) AI Genie Review: https://sumonreview.com/ai-genie-review
(2) SocioWave Review: https://sumonreview.com/sociowave-review
(3) AI Partner & Profit Review: https://sumonreview.com/ai-partner-profit-review
(4) AI Ebook Suite Review: https://sumonreview.com/ai-ebook-suite-review
#AIFusionBuddyReview,
#AIFusionBuddyFeatures,
#AIFusionBuddyPricing,
#AIFusionBuddyProsandCons,
#AIFusionBuddyTutorial,
#AIFusionBuddyUserExperience
#AIFusionBuddyforBeginners,
#AIFusionBuddyBenefits,
#AIFusionBuddyComparison,
#AIFusionBuddyInstallation,
#AIFusionBuddyRefundPolicy,
#AIFusionBuddyDemo,
#AIFusionBuddyMaintenanceFees,
#AIFusionBuddyNewbieFriendly,
#WhatIsAIFusionBuddy?,
#HowDoesAIFusionBuddyWorks
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.
E-commerce Application Development Company.pdfHornet Dynamics
Your business can reach new heights with our assistance as we design solutions that are specifically appropriate for your goals and vision. Our eCommerce application solutions can digitally coordinate all retail operations processes to meet the demands of the marketplace while maintaining business continuity.
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
Software Engineering, Software Consulting, Tech Lead, Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Transaction, Spring MVC, OpenShift Cloud Platform, Kafka, REST, SOAP, LLD & HLD.
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/
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.
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.
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.
9. Predicate - checks property of type A
case class Predicate[A](fun: A => Boolean)
9
10. Predicate - complicated one ;)
case class Predicate[A](fun: A => Boolean)
val hasEnoughLength: Predicate[Int] = Predicate(a => a > 3)
10
11. Can we use length to create Predicate[String]?
case class Predicate[A](fun: A => Boolean)
val hasEnoughLength: Predicate[Int] = Predicate(a => a > 3)
def len(s: String): Int = s.length
val isValidCode: Predicate[String] = ???
11
12. Predicate - can we map (define Functor)?
case class Predicate[A](fun: A => Boolean)
import cats.Functor
val predicateFuncor: Functor[Predicate] = new Functor[Predicate] {
def map[A, B](fa: Predicate[A])(f: A => B): Predicate[B] = ???
}
12
13. Predicate - but we can prepend!
case class Predicate[A](fun: A => Boolean)
val hasEnoughLength: Predicate[Int] = Predicate(a => a > 3)
def len(s: String): Int = s.length
val isValidCode: Predicate[String] =
Predicate[String](len andThen hasEnoughLength.fun)
13
14. case class Predicate[A](fun: A => Boolean)
def contramap[A, B](pred: Predicate[A])(fba: B => A): Predicate[B] =
Predicate[B](fba andThen pred.fun)
Predicate - generalize prepend
14
16. Example2 - Can we reuse existing Show?
trait Show[A] {
def show(a: A): String
}
case class Processor(name: String)
case class Multicore(name: String, coreCount: Int)
val sp: Show[Processor] = new Show[Processor] {
override def show(a: Processor): String = s"Processor ${a.name}"
}
def asProcessor(mc: Multicore): Processor = Processor(s"${mc.coreCount} x ${mc.name}")
16
17. Example2 - Can we define Functor for Show?
trait Show[A] {
def show(a: A): String
}
val showFunctor: Functor[Show] = new Functor[Show] {
override def map[A, B](fa: Show[A])(f: A => B): Show[B] = ???
}
17
18. Example2 - no! but we can prepend
trait Show[A] {
def show(a: A): String
}
def contramap[A, B](fa: Show[A])(f: B => A): Show[B] = new Show[B] {
override def show(a: B): String = fa.show(f(a))
}
18
19. Common pattern - prepend to input 1/3
trait Show[A] {
def show(a: A): String
}
def prepend[A, B](fa: Show[A])(f: B => A): Show[B] = new Show[B] {
override def show(a: B): String = fa.show(f(a))
}
19
20. Common pattern - prepend to input 2/3
case class Predicate[A](fun: A => Boolean)
def prepend[A, B](pred: Predicate[A])(fba: B => A): Predicate[B] =
Predicate[B](fba andThen pred.fun)
20
21. Common pattern - prepend to input Contravariant
trait InputPrepender[F[_]] {
def prepend[A, B] (fa: F[A])(f: B => A): F[B]
}
21
22. Mathematicians and names :)
trait Contravariant[F[_]] {
def contramap[A, B] (fa: F[A])(f: B => A): F[B]
}
22
23. Contravariant - like a Functor but flip!
trait Functor[F[_]] {
def map[A, B] (fa: F[A]) (f: A => B): F[B]
}
trait Contravariant[F[_]] {
def contramap[A, B] (fa: F[A]) (f: B => A): F[B]
}
23
24. Contravariant Functor - input + ability to prepend
Functor is “full of” A’s (container A, function producing A)
F[A] we can map A => B and we get F[B]
F[A] we can contramap B => A and we get F[B]
Contravariant “needs” A (index of container, function
consuming A)
24
26. Exercises - Contravariant for scala.math.Equiv
trait Equiv[T] {
def equiv(x: T, y: T): Boolean
}
val EquivContra: Contravariant[Equiv] = new Contravariant[Equiv] {
override def contramap[A, B](fa: Equiv[A])(f: B => A): Equiv[B] = ???
}
Much more:
https://github.com/lemastero/contravariant_profunctor_exercises/blob/master/src/main/scala/contra_pro/Exercise1_Contravariant.
scala
26
27. Contravariant - example Function1
def function1Contravariant[R]: Contravariant[? => R] =
new Contravariant[? => R] {
def contramap[A, B](r: A => R)(f: B => A) = r compose f
}
27
28. Contravariant - example Function1
def function1Contravariant[R]: Contravariant[? => R] =
new Contravariant[? => R] {
def contramap[A, B](r: A => R)(f: B => A) = r compose f
}
Glorified compose of Function1 !!!
28
30. Contravariant - example Reader - Functor
case class Reader[C, V](run: C => V)
def readerFunctor[C] = new Functor[Reader[C,?]] {
def map[A, B](x: Reader[C, A])(f: A => B): Reader[C, B] =
Reader(x.run andThen f)
}
30
31. Contravariant - example Reader - Monad
case class Reader[C, V](run: C => V)
def readerMonad[C] = new Monad[Reader[C, ?]] {
def map[A, B](x: Reader[C, A])(f: A => B): Reader[C, B] =
Reader(x.run andThen f)
def pure[A](a: A): Reader[C, A] =
new Reader(_ => a)
def flatMap[A, B](ma: Reader[C, A])(f: A => Reader[C, B]) = ???
}
31
32. Contravariant - example Reader - Contravariant
case class Reader[C, V](run: C => V)
def readerContra[V] = new Contravariant[Reader[?, V]] {
def contramap[A, B](fa: Reader[A, V])(f: B => A):
Reader[B, V] = Reader(f andThen fa.run)
}
32
33. Functor laws
fmap id = id
fmap f . fmap g = fmap (f . g)
Contravariant laws
contramap id = id
contramap f . contramap g = contramap (g . f)
Contravariant - laws in Haskell
33
36. Contravariant - FunctionN parameters all but last
trait Function2[-T1, -T2, +R]{
def apply(v1: T1, v2: T2): R
}
trait Function3[-T1, -T2, -T3, +R]{
def apply(v1: T1, v2: T2, v3: T3): R
}
//...
All parameters are in negative position, co we could define Contravariant
instance for it.
(Or even BiContravariant, TriContravariant, ... if they existed :)
36
37. Contravariant * Contravariant = Covariant
Compose contravariant functors:
https://github.com/typelevel/cats/blob/master/core/src/main/scala/cats/Contravariant.scala#L11-L15
Input of your input is not my input
But it’s input is ...
https://github.com/lemastero/scala_typeclassopedia/blob/master/src/main/scala/contravariant/HoFStructure.scala
37
39. Contravariant Functors everywhere but why?
We don’t want to map … and change HttpApi[Json] into HttpApi[Ints]
We might want to:
● provide part of configuration
● change config file path to parsed case class with configuration
● set execution context for all operations
● provide dependency like AvroKafkaDeserializer and schema registry config
(clients don’t have to worry about it)
● add defaults and require only Option[Config]
● ...
39
40. Contravariant - examples in open source libs
Encoder in Scodec:
github.com/scodec/scodec/blob/series/1.11.x/shared/src/main/scala/scodec/Encoder.scala#L40-L47
Schedule/ZSink/ZQueue in ZIO (contramap, provideSome):
https://github.com/zio/zio/search?q=contramap&unscoped_q=contramap
Logger
https://github.com/zio/zio-logging/issues/7
JSON Encoder in Circe
https://github.com/circe/circe/blob/master/modules/core/shared/src/main/scala/io/circe/Encoder.scala#L53-L55
40
44. case class Serializer[A](run: A => Array[Byte])
val strSerial = Serializer[String](_.getBytes)
val intSerial = Serializer[Int](_.toString.getBytes)
GOTO Github:
https://github.com/lemastero/contravariant_profunctor_exercises/blob/master/src/test/scala/contra_pro/DivideSpec.scala
Divide (1) - Serialization
44
45. val fragmentSerial = Serializer[Fragment] { frag =>
val a1 = strSerial.run(frag.name)
val a2 = intSerial.run(frag.size)
a1 ++ a2
}
val serialized = fragmentSerial.run(Fragment("Area", 52))
new String(serialized ) mustBe "Area52"
Divide (2) - How to combine serializers?
45
51. Define full laws for Divide as in Haskell
hackage.haskell.org/package/contravariant/docs/Data-Functor-Contravariant-Divisible.html#g:4
Not simplified as in Scalaz and Cats!
Contravariant - Divide - Challenge
51
57. Good general theory does not search for the maximum
generality, but for the right generality.
Saunders Mac Lane
Choose the right level of abstraction, to see the
problem more clearly
Eugenia Cheng, Category in Life
https://www.youtube.com/watch?v=ho7oagHeqNc
Thank you :)
57