- The speaker discusses trends towards better support for asynchronous programming in various languages like Kotlin, Java, and others.
- This makes a direct style of programming using things like delimited continuations more attractive. It will influence libraries and frameworks.
- The talk presents work on building foundations for direct style reactive programming in Scala based on things like boundaries/breaks, suspensions, and asynchronous sources like futures and channels.
- This approach provides simpler composition than monads and avoids problems of current futures implementations. It opens up new techniques for concurrency and asynchronous programming.
Functional Domain Modeling - The ZIO 2 WayDebasish Ghosh
Principled way to design and implement functional domain models using some of the patterns of domain driven design. DDD, as the name suggests, is focused towards the domain model and the patterns of architecture that it encourages are also based on how we think of interactions amongst the basic abstractions of the domain. Of course the primary goal of the talk is to discuss how Scala and Zio 2 can be a potent combination in realizing the implementation of such models. This is not a talk on FP, the focus will be on how to structure and modularise an application based on some of the patterns of DDD.
The document discusses monads and functional programming concepts. It begins by explaining that monads are structures that put values in computational contexts. It then provides a technical definition of a monad involving endofunctors, natural transformations, and laws. Several examples are given to illustrate monads, including the Optional monad in Java to handle null values, and the Stream monad to represent sequences. The document advocates using monads to make aspects like errors, state, and effects explicit in a program's type system.
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
This document discusses domain modeling in a functional world based on the speaker's real life experiences. The speaker covers topics like immutability and algebraic data types, updating domain models functionally using lenses, type classes for domain modeling, and managing states functionally. The speaker advocates for isolating pure domain logic from side effects to make the logic easier to test, reason about, and parallelize. Functional composition is emphasized as a way to build complex abstractions from simpler ones.
The document discusses functional and algebraic domain modeling. It defines an algebraic structure as a set with operations that satisfy axioms. Domain modeling involves identifying types, functions between types, and rules that govern the domain. A bounded context models a consistent vocabulary and behaviors as functions on domain objects. The algebra of a type refers to the number of possible inhabitants based on its structure. Product and sum types are discussed as ways to model heterogeneous data. Algebras of types and functions can be composed to build larger behaviors by following type relationships. An approach to domain modeling uses algebraic composition of identified behaviors to implement and modularize domain models.
Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Ha...Philip Schwarz
- The document describes how product types (built using AND) and sum types (built using OR) are used to define types for representing fruit salads and fruit snacks in F#, Haskell, Scala, and Java.
- Product types combine elements and are used to define the FruitSalad type, while sum types allow alternatives and are used to define the FruitSnack type consisting of different fruits.
- Pattern matching is demonstrated to write functions that analyze and return different strings based on the values of FruitSalad and FruitSnack types.
Functional Domain Modeling - The ZIO 2 WayDebasish Ghosh
Principled way to design and implement functional domain models using some of the patterns of domain driven design. DDD, as the name suggests, is focused towards the domain model and the patterns of architecture that it encourages are also based on how we think of interactions amongst the basic abstractions of the domain. Of course the primary goal of the talk is to discuss how Scala and Zio 2 can be a potent combination in realizing the implementation of such models. This is not a talk on FP, the focus will be on how to structure and modularise an application based on some of the patterns of DDD.
The document discusses monads and functional programming concepts. It begins by explaining that monads are structures that put values in computational contexts. It then provides a technical definition of a monad involving endofunctors, natural transformations, and laws. Several examples are given to illustrate monads, including the Optional monad in Java to handle null values, and the Stream monad to represent sequences. The document advocates using monads to make aspects like errors, state, and effects explicit in a program's type system.
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
This document discusses domain modeling in a functional world based on the speaker's real life experiences. The speaker covers topics like immutability and algebraic data types, updating domain models functionally using lenses, type classes for domain modeling, and managing states functionally. The speaker advocates for isolating pure domain logic from side effects to make the logic easier to test, reason about, and parallelize. Functional composition is emphasized as a way to build complex abstractions from simpler ones.
The document discusses functional and algebraic domain modeling. It defines an algebraic structure as a set with operations that satisfy axioms. Domain modeling involves identifying types, functions between types, and rules that govern the domain. A bounded context models a consistent vocabulary and behaviors as functions on domain objects. The algebra of a type refers to the number of possible inhabitants based on its structure. Product and sum types are discussed as ways to model heterogeneous data. Algebras of types and functions can be composed to build larger behaviors by following type relationships. An approach to domain modeling uses algebraic composition of identified behaviors to implement and modularize domain models.
Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Ha...Philip Schwarz
- The document describes how product types (built using AND) and sum types (built using OR) are used to define types for representing fruit salads and fruit snacks in F#, Haskell, Scala, and Java.
- Product types combine elements and are used to define the FruitSalad type, while sum types allow alternatives and are used to define the FruitSnack type consisting of different fruits.
- Pattern matching is demonstrated to write functions that analyze and return different strings based on the values of FruitSalad and FruitSnack types.
This document provides an overview of functional programming concepts including:
- Functional programming focuses on immutable data and treating computation as mathematical functions. It emphasizes eliminating side effects.
- Key concepts include first-class functions, higher-order functions, pure functions, recursion, currying, and pattern matching.
- Functional programming languages often use immutable data, recursion instead of looping, and avoid mutable state through techniques like immutable data structures and actor models.
Constructors and destructors in Python.
Constructors are special methods that are called automatically when an object is created. They initialize variables and ensure objects are properly initialized. There are two types of constructors: default and parameterized. Default don't take arguments, parameterized do.
Destructors are called when an object is destroyed. Defined using __del__(), they are useful for releasing resources like closing files before a program exits.
The document then provides code examples of classes with constructors, parameterized constructors, and destructors. It also discusses Python's garbage collection and how the collector deletes unneeded objects to free memory space.
The document discusses object-oriented programming (OOP) and functional programming (FP). It argues that OOP and FP are not opposites and can be effectively combined. It addresses common myths about FP, such as that it is new, hard, or only suitable for mathematical problems. The document also compares how OOP and FP approach concepts like decomposition, composition, error handling, and mutability/referential transparency. While both approaches have merits, the document concludes there is no single best approach and the choice depends on the problem and programmer preferences.
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
Algebraic Thinking for Evolution of Pure Functional Domain ModelsDebasish Ghosh
The focus of the talk is to emphasize the importance of algebraic thinking when designing pure functional domain models. The talk begins with the definition of an algebra as consisting of a carrier type, a set of operations/functions and a set of laws on those operations. Using examples from the standard library, the talk shows how thinking of abstractions in terms of its algebra is more intuitive than discussing its operational semantics. The talk also discusses the virtues of parametricity and compositionality in designing proper algebras.
Algebras are compositional and help build larger algebras out of smaller ones. We start with base level types available in standard libraries and compose larger programs out of them. We take a real life use case for a domain model and illustrate how we can define the entire model using the power of algebraic composition of the various types. We talk about how to model side-effects as pure abstractions using algebraic effects. At no point we will talk about implementations.
At the end of the talk we will have a working model built completely out of the underlying algebra of the domain language.
Scala Intro training @ Lohika, Odessa, UA.
This is a basic Scala Programming Language overview intended to evangelize the language among any-language programmers.
This document provides an overview of Java generics through examples. It begins with simple examples demonstrating how generics can be used to define container classes (BoxPrinter) and pair classes (Pair). It discusses benefits like type safety and avoiding duplication. Further examples show generics with classes, methods, and limitations like erasure. Wildcard types are introduced as a way to overcome some limitations. Key points covered include generic methods, wildcards, raw types and warnings, limitations of wildcards, and issues with readability of generic code.
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 1Philip Schwarz
slides can look grainy and/or out of focus when seen on slideshare - download for flawless quality - Based on Scott Wlaschin’s great book 'Domain Modeling Made Functional' and on Martin Odersky's talk 'A Tour of Scala 3'.
From object oriented to functional domain modelingMario Fusco
This document discusses moving from an object-oriented approach to a functional approach for domain modeling. It provides examples of modeling a bank account and salary calculator in both OOP and FP styles. Some key benefits of the functional approach highlighted include immutability, avoiding side effects, handling errors through monads instead of exceptions, and composing functions together through currying and composition. Overall the document advocates that while OOP and FP both have merits, modeling as functions can provide advantages in terms of understandability, testability, and extensibility of the code.
The document discusses lambda expressions in Java 8. It defines lambda expressions as anonymous functions that can be passed around as method parameters or returned from methods. Lambda expressions allow treating functions as first-class citizens in Java by letting functions be passed around as arguments to other functions. The document provides examples of lambda expressions in Java 8 and how they can be used with functional interfaces, method references, the forEach() method, and streams. It also discusses scope and type of lambda expressions and provides code samples demonstrating streams and stream pipelines.
Frameworks are bulky, quirky, and non-compositional, which has led to a rejection of Spring and similar frameworks in the Scala ecosystem. Yet, despite their drawbacks, frameworks have been used to boost team productivity in many large companies. In this presentation, Pavel and Kai will introduce Izumi 1.0, a Scala microframework based on compositional functional programming. Designed to help you and your team achieve new levels of productivity, Izumi now includes full compile-time checks for your configurable applications and completely reworked Tagless Final hierarchy for Bifunctors and Trifunctors.
The iterator design pattern provides a way to access elements of an aggregate object sequentially without exposing its underlying representation. It hides implementation details and allows for different traversals while separating traversal code from the list itself. The pattern involves an iterator interface with methods like first(), next(), and isDone(), and an aggregate that creates an iterator and returns it. Iterators can be external, controlled by the client, or internal, controlling iteration themselves through anonymous functions or closures.
Les versions 19 et 20 de Java, publiées en septembre et mars derniers, sont les 10eme et 11eme release en application du modèle de release tous les 6 mois.
En attendant la publication de Java 21, la prochaine version LTS publiée en septembre de cette année, et pour en donner quelques aperçus, cette présentation brosse une revue détaillée des nouveautés introduites dans ces nouvelles versions non-LTS de Java, issues des projets Amber, Panama et Loom d’OpenJDK ainsi que des fonctionnalités non incluses dans des JEPs.
If You Think You Can Stay Away from Functional Programming, You Are WrongMario Fusco
The document discusses several key concepts in functional programming including:
- Immutable data and pure functions avoid side effects and allow for referential transparency.
- Higher order functions and avoiding mutable state enable concurrency and parallelism without data races.
- Programs can be designed with a pure functional core and push side effects to the outer layers for modularity.
Functors, Applicatives and Monads In ScalaKnoldus Inc.
The document discusses functors, applicatives, and monads. It defines each concept and provides examples. Functors allow mapping a function over a wrapped value using map. Applicatives allow applying a function wrapped in a context to a value wrapped in a context using apply. Monads allow applying a function that returns a wrapped value to a wrapped value using flatMap. Examples of each include Option for functors, lists for applicatives, and futures for monads.
This document discusses recursive functions, which are functions that call themselves repetitively until a certain condition is satisfied. It provides an introduction to recursive functions, noting that they contain statements to determine if the function should call itself again, a function call with arguments, a conditional statement like if/else, and a return statement. It then provides two examples of recursive functions as class work: writing a program to find the product of two numbers recursively and writing a program to calculate a^b recursively.
The document is a presentation on lambda expressions in Java 8 given by Isaac Carter. It introduces lambda expressions and functional programming concepts in Java 8 such as functional interfaces, streams, and method references. It provides examples of using lambda expressions with common Java 8 APIs like forEach(), Predicate, and stream(). The presentation emphasizes thinking declaratively rather than imperatively in Java 8 and leveraging lambda expressions to let Java do more of the work.
The document discusses Scala reflection, which provides a unified API to access information about a program at both compile-time and runtime. This reflection API exposes compiler trees, symbols, and types through universes, mirrors, and symbols. It allows programs to inspect and analyze themselves, defeat erasure, and even compile code at runtime or compile-time through macros. The reflection features are available in Scala 2.10 and aim to give programs almost as much insight into themselves as the compiler has.
The document discusses Scala reflection, which provides a unified API to access information about a program at both compile-time and runtime. This API allows programs to inspect their structure, types, and symbols using trees, mirrors, and universes. It facilitates tasks like runtime compilation, reifying types, and writing macros. The current implementation is available in Scala 2.10 M3, with runtime reflection improved for the upcoming M4 release.
This document provides an overview of functional programming concepts including:
- Functional programming focuses on immutable data and treating computation as mathematical functions. It emphasizes eliminating side effects.
- Key concepts include first-class functions, higher-order functions, pure functions, recursion, currying, and pattern matching.
- Functional programming languages often use immutable data, recursion instead of looping, and avoid mutable state through techniques like immutable data structures and actor models.
Constructors and destructors in Python.
Constructors are special methods that are called automatically when an object is created. They initialize variables and ensure objects are properly initialized. There are two types of constructors: default and parameterized. Default don't take arguments, parameterized do.
Destructors are called when an object is destroyed. Defined using __del__(), they are useful for releasing resources like closing files before a program exits.
The document then provides code examples of classes with constructors, parameterized constructors, and destructors. It also discusses Python's garbage collection and how the collector deletes unneeded objects to free memory space.
The document discusses object-oriented programming (OOP) and functional programming (FP). It argues that OOP and FP are not opposites and can be effectively combined. It addresses common myths about FP, such as that it is new, hard, or only suitable for mathematical problems. The document also compares how OOP and FP approach concepts like decomposition, composition, error handling, and mutability/referential transparency. While both approaches have merits, the document concludes there is no single best approach and the choice depends on the problem and programmer preferences.
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
Algebraic Thinking for Evolution of Pure Functional Domain ModelsDebasish Ghosh
The focus of the talk is to emphasize the importance of algebraic thinking when designing pure functional domain models. The talk begins with the definition of an algebra as consisting of a carrier type, a set of operations/functions and a set of laws on those operations. Using examples from the standard library, the talk shows how thinking of abstractions in terms of its algebra is more intuitive than discussing its operational semantics. The talk also discusses the virtues of parametricity and compositionality in designing proper algebras.
Algebras are compositional and help build larger algebras out of smaller ones. We start with base level types available in standard libraries and compose larger programs out of them. We take a real life use case for a domain model and illustrate how we can define the entire model using the power of algebraic composition of the various types. We talk about how to model side-effects as pure abstractions using algebraic effects. At no point we will talk about implementations.
At the end of the talk we will have a working model built completely out of the underlying algebra of the domain language.
Scala Intro training @ Lohika, Odessa, UA.
This is a basic Scala Programming Language overview intended to evangelize the language among any-language programmers.
This document provides an overview of Java generics through examples. It begins with simple examples demonstrating how generics can be used to define container classes (BoxPrinter) and pair classes (Pair). It discusses benefits like type safety and avoiding duplication. Further examples show generics with classes, methods, and limitations like erasure. Wildcard types are introduced as a way to overcome some limitations. Key points covered include generic methods, wildcards, raw types and warnings, limitations of wildcards, and issues with readability of generic code.
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 1Philip Schwarz
slides can look grainy and/or out of focus when seen on slideshare - download for flawless quality - Based on Scott Wlaschin’s great book 'Domain Modeling Made Functional' and on Martin Odersky's talk 'A Tour of Scala 3'.
From object oriented to functional domain modelingMario Fusco
This document discusses moving from an object-oriented approach to a functional approach for domain modeling. It provides examples of modeling a bank account and salary calculator in both OOP and FP styles. Some key benefits of the functional approach highlighted include immutability, avoiding side effects, handling errors through monads instead of exceptions, and composing functions together through currying and composition. Overall the document advocates that while OOP and FP both have merits, modeling as functions can provide advantages in terms of understandability, testability, and extensibility of the code.
The document discusses lambda expressions in Java 8. It defines lambda expressions as anonymous functions that can be passed around as method parameters or returned from methods. Lambda expressions allow treating functions as first-class citizens in Java by letting functions be passed around as arguments to other functions. The document provides examples of lambda expressions in Java 8 and how they can be used with functional interfaces, method references, the forEach() method, and streams. It also discusses scope and type of lambda expressions and provides code samples demonstrating streams and stream pipelines.
Frameworks are bulky, quirky, and non-compositional, which has led to a rejection of Spring and similar frameworks in the Scala ecosystem. Yet, despite their drawbacks, frameworks have been used to boost team productivity in many large companies. In this presentation, Pavel and Kai will introduce Izumi 1.0, a Scala microframework based on compositional functional programming. Designed to help you and your team achieve new levels of productivity, Izumi now includes full compile-time checks for your configurable applications and completely reworked Tagless Final hierarchy for Bifunctors and Trifunctors.
The iterator design pattern provides a way to access elements of an aggregate object sequentially without exposing its underlying representation. It hides implementation details and allows for different traversals while separating traversal code from the list itself. The pattern involves an iterator interface with methods like first(), next(), and isDone(), and an aggregate that creates an iterator and returns it. Iterators can be external, controlled by the client, or internal, controlling iteration themselves through anonymous functions or closures.
Les versions 19 et 20 de Java, publiées en septembre et mars derniers, sont les 10eme et 11eme release en application du modèle de release tous les 6 mois.
En attendant la publication de Java 21, la prochaine version LTS publiée en septembre de cette année, et pour en donner quelques aperçus, cette présentation brosse une revue détaillée des nouveautés introduites dans ces nouvelles versions non-LTS de Java, issues des projets Amber, Panama et Loom d’OpenJDK ainsi que des fonctionnalités non incluses dans des JEPs.
If You Think You Can Stay Away from Functional Programming, You Are WrongMario Fusco
The document discusses several key concepts in functional programming including:
- Immutable data and pure functions avoid side effects and allow for referential transparency.
- Higher order functions and avoiding mutable state enable concurrency and parallelism without data races.
- Programs can be designed with a pure functional core and push side effects to the outer layers for modularity.
Functors, Applicatives and Monads In ScalaKnoldus Inc.
The document discusses functors, applicatives, and monads. It defines each concept and provides examples. Functors allow mapping a function over a wrapped value using map. Applicatives allow applying a function wrapped in a context to a value wrapped in a context using apply. Monads allow applying a function that returns a wrapped value to a wrapped value using flatMap. Examples of each include Option for functors, lists for applicatives, and futures for monads.
This document discusses recursive functions, which are functions that call themselves repetitively until a certain condition is satisfied. It provides an introduction to recursive functions, noting that they contain statements to determine if the function should call itself again, a function call with arguments, a conditional statement like if/else, and a return statement. It then provides two examples of recursive functions as class work: writing a program to find the product of two numbers recursively and writing a program to calculate a^b recursively.
The document is a presentation on lambda expressions in Java 8 given by Isaac Carter. It introduces lambda expressions and functional programming concepts in Java 8 such as functional interfaces, streams, and method references. It provides examples of using lambda expressions with common Java 8 APIs like forEach(), Predicate, and stream(). The presentation emphasizes thinking declaratively rather than imperatively in Java 8 and leveraging lambda expressions to let Java do more of the work.
The document discusses Scala reflection, which provides a unified API to access information about a program at both compile-time and runtime. This reflection API exposes compiler trees, symbols, and types through universes, mirrors, and symbols. It allows programs to inspect and analyze themselves, defeat erasure, and even compile code at runtime or compile-time through macros. The reflection features are available in Scala 2.10 and aim to give programs almost as much insight into themselves as the compiler has.
The document discusses Scala reflection, which provides a unified API to access information about a program at both compile-time and runtime. This API allows programs to inspect their structure, types, and symbols using trees, mirrors, and universes. It facilitates tasks like runtime compilation, reifying types, and writing macros. The current implementation is available in Scala 2.10 M3, with runtime reflection improved for the upcoming M4 release.
The document provides an overview of concurrency constructs and models. It discusses threads and locks, and some of the problems with locks like manually locking/unlocking and lock ordering issues. It then covers theoretical models like actors, CSP, and dataflow. Implementation details and problems with different models are discussed. Finally, it highlights some open problems and areas for further work.
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 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.
Slides from my "Swift, Swiftly" session at Øredev 2014.
Revealed by Apple in June of this year, the Swift programming language has already established itself as a huge leap forward for iOS and OS X developers. Learn the ins and outs of this new language, see how it compares to other modern OO languages, and hear about how Apple developers are using Swift to achieve new levels of productivity and efficiency.
Full video available: http://oredev.org/2014/sessions/swift-swiftly
Interfaces in Java allow classes to define common behaviors without inheritance. An interface defines abstract methods and constants but provides no implementation. A class implements an interface by providing method bodies for the abstract methods. Interfaces allow for multiple inheritance of behaviors. Default methods were added in Java 8 to allow interfaces to define method implementations for existing classes to optionally use.
The document discusses Intel Threading Building Blocks (TBB), a C++ template library for parallel programming. TBB provides features like parallel_for to simplify parallelizing loops across CPU cores without needing expertise in threads. It uses generic programming principles and provides common parallel algorithms, concurrent data structures, and task scheduling to make parallel programming more accessible and scalable. The example shows converting a serial velocity update loop to parallel using TBB.
The document discusses Intel Threading Building Blocks (TBB), a C++ template library for parallel programming. TBB provides features like parallel_for to simplify parallelizing loops across CPU cores without managing threads directly. It uses generic programming principles and provides common parallel algorithms, concurrent data structures, and synchronization primitives to make parallel programming more accessible. TBB aims to improve both correctness through avoiding race conditions and performance through efficient hardware utilization.
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfkarymadelaneyrenne19
Abstract Data Types
(a) Explain briefly what is meant by the term abstract data type (ADT). Give two
reasons why use of ADTs is good programming practice.
(b) Write out a signature, or interface, that defines the operations of a stack ADT.
(c) Consider a string of characters of the form
... (.( ... ).) ...
where ... indicates an arbitrary sequence of characters (except for parentheses),
(.( indicates an arbitrary number (one or more) of opening parentheses, and
similarly ).) indicates an arbitrary number of closing parentheses.
Using only the stack abstraction operations defined above, write pseudocode for
an algorithm that determines, using a stack, whether or not the number of closing
parentheses is the same as the number of opening parentheses.
You may assume the existence of a function read(str,ch) that reads the next character
of string str into ch.
You may also assume that you can invoke a function reportFail, that will cause
termination with failure, and similarly, reportSuccess causes termination with a
success indication.
Further, you may also assume that you can call a function newStack(S) to create
a new empty stack S, and eos(str) that returns false when you reach the end of
the string.
Solution
(a) Explain briefly what is meant by the term abstract data type (ADT). Give two
reasons why use of ADTs is good programming practice.
A data type is a collection of values and a set of operations on those values. That collection and
these operations form a mathematical construct that may be implemented with the use of a
particular hardware or software data structure. The term abstract data type (ADT) refers to the
basic mathematical concept that defines the data type. We have discussed four different
implementations of the list data structure.
In case of implementation of the list with the use of an array, the size of the array gives difficulty
if increased.
To avoid this, we allocate memory dynamically for nodes before connecting these nodes with the
help of pointers.
For this purpose, we made a singly linked list and connected it with the next pointer to make a
chain.
Moving forward is easy but going back is a difficult task.
To overcome this problem, we made a doubly linked list using prev andnext pointers. With the
help of these pointers, we can move forward and backward very easily. Now we face another
problem that the prev pointer of first node and the next pointer of the last node are NULL.
Therefore, we have to be careful in case of NULL pointers. To remove the NULL pointers, we
made the circular link list by connecting the first and last node.
The program employing the list data structure is not concerned with its implementation.
We do not care how the list is being implemented whether through an array, singly linked list,
doubly linked list or circular linked list. It has been witnessed that in these four implementations
of the list, the interface remained the same i.e. it implements the same methods like add, get,
next, start a.
- Scala is being adopted for web platforms, trading platforms, financial modeling, and simulation. Scala 2.9 includes improvements to parallel and concurrent computing libraries as well as faster compilation.
- Play Framework 2.0 will move to a Scala core while retaining Java support. The Scala Eclipse IDE has been reworked for better reliability and responsiveness.
- Scala 2.10 will include a new reflection framework and other IDE improvements. Avoiding mutable state enables functional and parallel programming. Scala supports both parallelism and concurrency through tools like parallel collections and actors.
- Future work includes distributed collections, parallel domain-specific languages, and unifying the Scala compiler and reflection APIs. Scal
The document summarizes ParaSail, a new parallel specification and implementation language designed for high-integrity systems. Key points include:
- ParaSail aims to simplify, unify, parallelize concepts from existing languages and add formal verification capabilities.
- It is designed to make parallelism the default and make sequential execution optional.
- ParaSail includes assertions, pre/postconditions, and other annotations to enable fully formal verification at compile-time with no run-time checking.
MATLAB stands for Matrix Laboratory. MATLAB was written originally
to provide easy access to matrix software developed by the LINPACK (linear system package) and matlab 2012a manual pdf
This presentation describes some key features of Scala uses in the creation of machine learning algorithms:
1 Functorial definition of tensors for learning non-linear models (manifolds)
2. Monads to compose of explicit kernel functions in Euclidean space
3. Implicit class to extends Scala standard library
4. Stackable traits and dependency injection to build formal models and dynamic workflows
5. Tail recursion to implementation dynamic programming techniques
6. Streaming to reduce memory consumption for big data
7. Control of back pressure in data flows
http://patricknicolas.blogspot.com
http://bit.ly/12GjRu9
This document discusses various design patterns in Python and how they compare to their implementations in other languages like C++. It provides examples of how common patterns from the Gang of Four book like Singleton, Observer, Strategy, and Decorator are simplified or invisible in Python due to features like first-class functions and duck typing. The document aims to illustrate Pythonic ways to implement these patterns without unnecessary complexity.
This ppt describes basics of scala upto collections covering both object oriented and functional programming concepts of the language.
References:Scala cookbook
Rust provides both control and safety through its ownership and borrowing model. It enforces safe patterns using the type system to prevent issues like data races, use-after-free errors, and iterator invalidation. This is achieved with no runtime overhead. Rust also supports building efficient abstractions through features like zero-cost abstractions and its approach to concurrency that guarantees freedom from data races. While Rust borrows ideas from other languages, its type system and ownership rules allow building applications that have control without compromising on safety.
Fuel Up JavaScript with Functional ProgrammingShine Xavier
JavaScript is the lingua franca of web development for over a decade. It has evolved tremendously along with the Web and has entrenched in modern browsers, complex Web applications, mobile development, server-side programming, and in emerging platforms like the Internet of Things.
Eventhough JavaScript has come a long way, a reinforced makeover to it will help build concurrent and massive systems that handle Big Data, IoT peripherals and many other complex eco systems. Functional Programming is the programming paradigm that could empower JavaScript to to enable more effective, robust, and flexible software development.
These days, Functional Programming is at the heart of every new generation programming technologies. The inclusion of Functional Programming in JavaScript will lead to advanced and futuristic systems.
The need of the hour is to unwrap the underlying concepts and its implementation in the software development process.
The 46th edition of FAYA:80 provides a unique opportunity for the JavaScript developers and technology enthusiasts to shed light on the functional programming paradigm and on writing efficient functional code in JavaScript.
Join us for the session to know more.
Topics Covered:
· Functional Programming Core Concepts
· Function Compositions & Pipelines
· Use of JS in Functional Programming
· Techniques for Functional Coding in JS
· Live Demo
This document outlines the roadmap for Scala 3 and the Dotty compiler. It discusses the goals of improving type safety, ergonomics and performance while simplifying the language. Key points include incorporating learnings from Haskell for purity without sacrificing simplicity. The roadmap aims for a 2020 release of Scala 3 with stabilization in 2019. It emphasizes the importance of community contributions and getting early feedback on Dotty releases.
This document discusses implicit function types as a way to abstract over context in programming. It proposes implicit function types as a lighter-weight alternative to type classes and the reader monad for passing implicit context parameters. Implicit function types allow context to be provided implicitly based on the expected type rather than requiring it to be passed explicitly. The document outlines the typing rules and translation to the lambda calculus for implicit function types and provides examples of their use in a conference management system and the builder pattern.
This document summarizes Martin Odersky's talk on implicits in Scala. The key points are:
1. Implicits allow certain values or functions to be passed implicitly rather than explicitly as parameters. This can avoid tedious repetition when many parameters rarely change.
2. Implicits are commonly used to establish context, inject dependencies, implement type classes, and prove theorems by modeling types as theorems and programs as proofs.
3. Future changes to implicits in Scala 3 include allowing multiple implicit parameter lists, implicit by-name parameters, and implicit function types which avoid wrapping implicits in monads.
- Implicit function types are a powerful way to abstract over contexts by defining types that inject implicit values into a scope. This can fundamentally change the code we write by removing boilerplate around passing implicit parameters and configurations.
- Implicit parameters are a core Scala feature that allow removing repetition through parameterization while enabling use cases like proving theorems, establishing context, and implementing type classes. Their scope may be expanded through implicit function types.
- Future Scala versions aim to tighten rules for implicit conversions while introducing features like lazy implicits, multiple implicit parameter lists, and coherence to improve the discoverability and reasoning around implicits.
This document summarizes Martin Odersky's talk on DOT and dotty. DOT is intended to be a minimal foundational calculus for Scala that can model type parameterization, modules, and objects/classes. DOT includes dependent types to model modules as objects with type members. The DOT type system includes function types, method declarations, type declarations, and intersections. DOT's soundness proof was challenging due to programmer-definable subtyping. Dotty is the new Scala compiler prototype built on DOT, supporting new features like union and intersection types while dropping some old features. Implicit function types in dotty allow abstracting over implicit contexts without boilerplate.
The document discusses four approaches to implementing higher-kinded types in the Dotty compiler: the simple encoding, projection encoding, refinement encoding, and direct representation. It describes each approach and its limitations. The simple encoding provides a modest way to support basic higher-kinded concepts but has difficulty explaining legality. The projection and refinement encodings had problems and were ultimately less successful than initially hoped. A direct representation of higher-kinded types through special type forms was needed for robust support. While compiler hacking validated ideas, a better theoretical foundation relating higher-kinded types to the DOT calculus may have avoided some experiments.
The document summarizes Martin Odersky's talk at Scala Days 2016 about the road ahead for Scala. The key points are:
1. Scala is maturing with improvements to tools like IDEs and build tools in 2015, while 2016 sees increased activity with the Scala Center, Scala 2.12 release, and rethinking Scala libraries.
2. The Scala Center was formed to undertake projects benefiting the Scala community with support from various companies.
3. Scala 2.12 focuses on optimizing for Java 8 and includes many new features. Future releases will focus on improving Scala libraries and modularization.
4. The DOT calculus provides a formal
The document discusses a new compiler architecture for the Dotty Scala Compiler (dsc) that takes inspiration from functional databases. The architecture treats all values as time-varying functions indexed by compilation phase. This allows the compiler to answer questions about program elements by looking up their meaning at a specific point in time. The core data types include time-indexed abstract syntax trees, types, references to declarations, and denotations, which capture the meaning of references. Caching is used to efficiently store and retrieve values across phases.
- Scala originated from Martin Odersky's work on functional programming languages like OCaml in the 1980s and 1990s. It was designed to combine object-oriented and functional programming in a practical way.
- Key aspects of Scala include being statically typed while also being flexible, its unified object and module system, and treating libraries as primary over language features.
- Scala has grown into an large ecosystem centered around the JVM and also targets JavaScript via Scala.js. Tooling continues to improve with faster compilers and new IDE support.
- Future work includes establishing TASTY as a portable intermediate representation, connecting Scala to formal foundations through the DOT calculus, and exploring new type
The document discusses the binary compatibility challenge in Scala and proposes using typed trees as a common intermediate format to address this issue. Currently, binary compatibility breaks cause problems when upgrading dependencies. The proposal is to compile to typed trees rather than bytecode, and distribute libraries as trees instead of bytecode. This would allow recompiling from trees as needed for compatibility, avoiding rebuilds but providing more flexibility than bytecode. It could improve efficiency of builds and enable cross-platform compilation.
Scala - The Simple Parts, SFScala presentationMartin Odersky
These are the slides of the talk I gave on May 22, 2014 to the San Francisco Scala user group. Similar talks were given before at GOTO Chicago, keynote, at Gilt Groupe and Hunter College in New York, at JAX Mainz and at FlatMap Oslo.
This document discusses the key building blocks that enable Scala to be a modular and growable language. It outlines seven simple parts of the Scala language itself that can be combined in flexible ways, including expressions, scopes, patterns, recursion, functions, collections, and variables. It also discusses seven library features like static types, objects, classes, traits, abstract types, type parameters, and implicit parameters that support modular programming. The document argues that this combination of simple language parts and library features allows Scala applications and libraries to smoothly grow from small to large systems.
This document discusses the key building blocks that enable Scala to be a modular and growable language. It outlines seven simple parts of the Scala language itself that can be combined in flexible ways, including expressions, scopes, patterns, recursion, function values, collections, and vars. It also lists seven features of Scala's type system that support modular programming, such as static typing, objects, classes, traits, abstract types, parameterized types, and implicit parameters. The document argues that this combination of simple language parts and powerful type features allows Scala programs and libraries to be composed modularly and to grow in complexity in a manageable way.
Oscon keynote: Working hard to keep it simpleMartin Odersky
The document discusses how Scala aims to make parallel and concurrent programming easier by avoiding mutable state and enabling a functional programming style, and it presents Scala as a language that unifies object-oriented and functional programming in a way that allows both sequential and parallel applications to be written safely and efficiently. Examples are given of how parallel collections and actors can be used in Scala for parallelism and concurrency, and how domain-specific languages embedded in Scala can help program parallel applications for different domains like physics simulation.
This document summarizes Martin Odersky's opening address at Scala eXchange in 2011 about the past, present and future of Scala. It discusses Scala's trajectory over the past 10 years from its initial development to widespread industrial adoption. It identifies concurrency and parallelism as a key concern going forward and outlines Scala's tools for both implicit and explicit parallel programming.
🏎️Tech Transformation: DevOps Insights from the Experts 👩💻campbellclarkson
Connect with fellow Trailblazers, learn from industry experts Glenda Thomson (Salesforce, Principal Technical Architect) and Will Dinn (Judo Bank, Salesforce Development Lead), and discover how to harness DevOps tools with Salesforce.
What is Continuous Testing in DevOps - A Definitive Guide.pdfkalichargn70th171
Once an overlooked aspect, continuous testing has become indispensable for enterprises striving to accelerate application delivery and reduce business impacts. According to a Statista report, 31.3% of global enterprises have embraced continuous integration and deployment within their DevOps, signaling a pervasive trend toward hastening release cycles.
Superpower Your Apache Kafka Applications Development with Complementary Open...Paul Brebner
Kafka Summit talk (Bangalore, India, May 2, 2024, https://events.bizzabo.com/573863/agenda/session/1300469 )
Many Apache Kafka use cases take advantage of Kafka’s ability to integrate multiple heterogeneous systems for stream processing and real-time machine learning scenarios. But Kafka also exists in a rich ecosystem of related but complementary stream processing technologies and tools, particularly from the open-source community. In this talk, we’ll take you on a tour of a selection of complementary tools that can make Kafka even more powerful. We’ll focus on tools for stream processing and querying, streaming machine learning, stream visibility and observation, stream meta-data, stream visualisation, stream development including testing and the use of Generative AI and LLMs, and stream performance and scalability. By the end you will have a good idea of the types of Kafka “superhero” tools that exist, which are my favourites (and what superpowers they have), and how they combine to save your Kafka applications development universe from swamploads of data stagnation monsters!
The Rising Future of CPaaS in the Middle East 2024Yara Milbes
Explore "The Rising Future of CPaaS in the Middle East in 2024" with this comprehensive PPT presentation. Discover how Communication Platforms as a Service (CPaaS) is transforming communication across various sectors in the Middle East.
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...Luigi Fugaro
Vector databases are transforming how we handle data, allowing us to search through text, images, and audio by converting them into vectors. Today, we'll dive into the basics of this exciting technology and discuss its potential to revolutionize our next-generation AI applications. We'll examine typical uses for these databases and the essential tools
developers need. Plus, we'll zoom in on the advanced capabilities of vector search and semantic caching in Java, showcasing these through a live demo with Redis libraries. Get ready to see how these powerful tools can change the game!
Voxxed Days Trieste 2024 - Unleashing the Power of Vector Search and Semantic...Luigi Fugaro
Vector databases are redefining data handling, enabling semantic searches across text, images, and audio encoded as vectors.
Redis OM for Java simplifies this innovative approach, making it accessible even for those new to vector data.
This presentation explores the cutting-edge features of vector search and semantic caching in Java, highlighting the Redis OM library through a demonstration application.
Redis OM has evolved to embrace the transformative world of vector database technology, now supporting Redis vector search and seamless integration with OpenAI, Hugging Face, LangChain, and LlamaIndex. This talk highlights the latest advancements in Redis OM, focusing on how it simplifies the complex process of vector indexing, data modeling, and querying for AI-powered applications. We will explore the new capabilities of Redis OM, including intuitive vector search interfaces and semantic caching, which reduce the overhead of large language model (LLM) calls.
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid
IBM watsonx Code Assistant for Z, our latest Generative AI-assisted mainframe application modernization solution. Mainframe (IBM Z) application modernization is a topic that every mainframe client is addressing to various degrees today, driven largely from digital transformation. With generative AI comes the opportunity to reimagine the mainframe application modernization experience. Infusing generative AI will enable speed and trust, help de-risk, and lower total costs associated with heavy-lifting application modernization initiatives. This document provides an overview of the IBM watsonx Code Assistant for Z which uses the power of generative AI to make it easier for developers to selectively modernize COBOL business services while maintaining mainframe qualities of service.
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...kalichargn70th171
In today's fiercely competitive mobile app market, the role of the QA team is pivotal for continuous improvement and sustained success. Effective testing strategies are essential to navigate the challenges confidently and precisely. Ensuring the perfection of mobile apps before they reach end-users requires thoughtful decisions in the testing plan.
Alluxio Webinar | 10x Faster Trino Queries on Your Data PlatformAlluxio, Inc.
Alluxio Webinar
June. 18, 2024
For more Alluxio Events: https://www.alluxio.io/events/
Speaker:
- Jianjian Xie (Staff Software Engineer, Alluxio)
As Trino users increasingly rely on cloud object storage for retrieving data, speed and cloud cost have become major challenges. The separation of compute and storage creates latency challenges when querying datasets; scanning data between storage and compute tiers becomes I/O bound. On the other hand, cloud API costs related to GET/LIST operations and cross-region data transfer add up quickly.
The newly introduced Trino file system cache by Alluxio aims to overcome the above challenges. In this session, Jianjian will dive into Trino data caching strategies, the latest test results, and discuss the multi-level caching architecture. This architecture makes Trino 10x faster for data lakes of any scale, from GB to EB.
What you will learn:
- Challenges relating to the speed and costs of running Trino in the cloud
- The new Trino file system cache feature overview, including the latest development status and test results
- A multi-level cache framework for maximized speed, including Trino file system cache and Alluxio distributed cache
- Real-world cases, including a large online payment firm and a top ridesharing company
- The future roadmap of Trino file system cache and Trino-Alluxio integration
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...kalichargn70th171
Visual testing plays a vital role in ensuring that software products meet the aesthetic requirements specified by clients in functional and non-functional specifications. In today's highly competitive digital landscape, users expect a seamless and visually appealing online experience. Visual testing, also known as automated UI testing or visual regression testing, verifies the accuracy of the visual elements that users interact with.
The Comprehensive Guide to Validating Audio-Visual Performances.pdfkalichargn70th171
Ensuring the optimal performance of your audio-visual (AV) equipment is crucial for delivering exceptional experiences. AV performance validation is a critical process that verifies the quality and functionality of your AV setup. Whether you're a content creator, a business conducting webinars, or a homeowner creating a home theater, validating your AV performance is essential.
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Paul Brebner
Closing talk for the Performance Engineering track at Community Over Code EU (Bratislava, Slovakia, June 5 2024) https://eu.communityovercode.org/sessions/2024/why-apache-kafka-clusters-are-like-galaxies-and-other-cosmic-kafka-quandaries-explored/ Instaclustr (now part of NetApp) manages 100s of Apache Kafka clusters of many different sizes, for a variety of use cases and customers. For the last 7 years I’ve been focused outwardly on exploring Kafka application development challenges, but recently I decided to look inward and see what I could discover about the performance, scalability and resource characteristics of the Kafka clusters themselves. Using a suite of Performance Engineering techniques, I will reveal some surprising discoveries about cosmic Kafka mysteries in our data centres, related to: cluster sizes and distribution (using Zipf’s Law), horizontal vs. vertical scalability, and predicting Kafka performance using metrics, modelling and regression techniques. These insights are relevant to Kafka developers and operators.
A neural network is a machine learning program, or model, that makes decisions in a manner similar to the human brain, by using processes that mimic the way biological neurons work together to identify phenomena, weigh options and arrive at conclusions.
Enhanced Screen Flows UI/UX using SLDS with Tom KittPeter Caitens
Join us for an engaging session led by Flow Champion, Tom Kitt. This session will dive into a technique of enhancing the user interfaces and user experiences within Screen Flows using the Salesforce Lightning Design System (SLDS). This technique uses Native functionality, with No Apex Code, No Custom Components and No Managed Packages required.
2. Shifting Foundations
Trends
Widespread support for async/await
Runtimes get better support for fibers or continuations.
Examples
Goroutines,
Project Loom in Java,
Kotlin coroutines,
OCaml or Haskell delimited continuations,
Research languages such as Effekt, Koka
Thesis of this talk
This will deeply influence libraries and frameworks
It’s very attractive now to go back to direct style.
3. Shifting Foundations
Trends
Widespread support for async/await
Runtimes get better support for fibers or continuations.
Examples
Goroutines,
Project Loom in Java,
Kotlin coroutines,
OCaml or Haskell delimited continuations,
Research languages such as Effekt, Koka
Thesis of this talk
This will deeply influence libraries and frameworks
It’s very attractive now to go back to direct style.
4. How will this influence Scala in the future?
1 There will likely be native foundations for direct-style reactive
programming
Delimited continuations on Scala Native
Fibers on latest Java
Source or bytecode rewriting for older Java, JS
2 This will enable new techniques for designing and composing
software
3 There will be a move away from monads as the primary way
of code composition.
5. Building a Direct-Style Stack
First step: Boundary/break
Error handling
Suspensions
Concurrency library design built on that
6. Building a Direct-Style Stack
First step: Boundary/break
(shipped)
Error handling
(enabled)
Suspensions
(wip)
Concurrency library design built on that
(wip)
7. Warmup: Boundary/break
A cleaner alternative to non-local returns (which will go away)
def firstIndex[T](xs: List[T], elem: T): Int =
boundary:
for (x, i) <- xs.zipWithIndex do
if x == elem then break(i)
-1
boundary establishes a boundary
break returns with a value from it.
9. API
package scala.util
object boundary:
final class Label[-T]
def break[T](value: T)(using label: Label[T]): Nothing =
throw Break(label, value)
inline def apply[T](inline body: Label[T] ?=> T): T = ...
end boundary
To break, you need a label that represents the boundary.
In a sense, label is a capability that enables to break.
(This is a common pattern)
10. Implementation
The implementation of break produces efficient code.
If break appears in the same stackframe as its boundary, use a
jump.
Otherwise use a fast exception that does not capture a stack
trace.
A stack trace is not needed since we know the exception will be
handled (*)
(*) To be 100% sure, this needs capture checking.
11. Implementation
The implementation of break produces efficient code.
If break appears in the same stackframe as its boundary, use a
jump.
Otherwise use a fast exception that does not capture a stack
trace.
A stack trace is not needed since we know the exception will be
handled (*)
(*) To be 100% sure, this needs capture checking.
12. Stage 2: Error handling
boundary/break can be used as the basis for flexible error handling.
For instance:
def firstColumn[T](xss: List[List[T]]): Option[List[T]] =
optional:
xss.map(_.headOption.?)
Optionally, returns the first column of the matrix xss.
Returns None if there is an empty row.
13. Error handling implementation
optional and ? on options can be implemented quite easily on top
of boundary/break:
object optional:
inline def apply[T](inline body: Label[None.type] ?=> T)
: Option[T] = boundary(Some(body))
extension [T](r: Option[T])
inline def ? (using label: Label[None.type]): T = r match
case Some(x) => x
case None => break(None)
Analogous implementations are possible for other result types such
as Either or a Rust-like Result.
My ideal way of error handling would be based on Result + ?.
14. Stage 3: Suspensions
Question: What if we could store the stack segment between a
break and its boundary and re-use it at some later time?
15. Suspensions
Question: What if we could store the stack segment between a
break and its boundary and re-use it at some later time?
This is the idea of delimited continuations.
16. Suspensions
Question: What if we could store the stack segment between a
break and its boundary and re-use it at some later time?
This is the idea of delimited continuations.
17. Suspension API
class Suspension[-T, +R]:
def resume(arg: T): R = ???
def suspend[T, R](body: Suspension[T, R] => R)(using Label[R]): T
Suspensions are quite powerful.
They can express at the same time algebraic effects and monads.
18. Generators
Python-style generators are a simple example of algebraic effects.
def example = Generator:
produce(”We’ll give you all the numbers divisible by 3 or 2”)
for i <- 1 to 1000 do
if i % 3 == 0 then
produce(s”$i is divisible by 3”)
else if i % 2 == 0 then
produce(s”$i is even”)
Here, Generator is essentially a simplified Iterator
trait Generator[T]:
def nextOption: Option[T]
19. Algebraic Effects
Task: Build a generate implementation of Generator, so that one
can compute the leafs of a Tree like this:
enum Tree[T]:
case Leaf(x: T)
case Inner(xs: List[Tree[T]])
def leafs[T](t: Tree[T]): Generator[T] =
generate: // effect scope
def recur(t: Tree[T]): Unit = t match
case Tree.Leaf(x) => produce(x) // effect
case Tree.Inner(xs) => xs.foreach(recur)
recur(t)
20. Generator Implementation
trait Produce[-T]:
def produce(x: T): Unit
def generate[T](body: Produce[T] ?=> Unit) = new Generator[T]:
def nextOption: Option[T] = step()
var step: () => Option[T] =
21. The Step Function
trait Produce[-T]: // effect type
def produce(x: T): Unit
def generate[T](body: Produce[T] ?=> Unit) = new Generator[T]:
def nextOption: Option[T] = step()
var step: () => Option[T] = () =>
boundary:
given Produce[T] with // handler
def produce(x: T): Unit =
suspend[Unit, Option[T]]: k =>
step = () => k.resume(())
Some(x)
body
None
22. Summary: Algebraic Effects
Effects are methods of effect traits
Handlers are implementations of effect traits
They are passed as implicit parameters.
They can abort part of a computation via break
They can also suspend part of a computation as a
continuation and resume it later.
23. Implementing Suspensions
There are several possibilities:
Directly in the runtime, as shown in the designs
On top of fibers (requires some compromises)
By bytecode rewriting (e.g. Quasar, javactrl)
By source rewriting
24. Suspensions and Monads:
Wadler (1993): Continuations can be expressed as a monad.
“Haskell is the essence of ML”
Filinski (1994): Every monad can be expressed in direct style
using just delimited continuations.
“ML is the essence of Haskell”
My take: designs based on continuations are simpler to compose
than monads.
25. Suspensions and Monads:
Wadler (1993): Continuations can be expressed as a monad.
“Haskell is the essence of ML”
Filinski (1994): Every monad can be expressed in direct style
using just delimited continuations.
“ML is the essence of Haskell”
My take: designs based on continuations are simpler to compose
than monads.
26. Direct-Style Futures
With suspend(*), we can implement lightweight and universal
await construct that can be called anywhere.
This can express simple, direct-style futures.
val sum = Future:
val f1 = Future(c1.read)
val f2 = Future(c2.read)
f1.value + f2.value
Structured concurrency: Local futures f1 and f2 complete before
sum completes. This might mean that one of them is cancelled if
the other returns with a failure.
(*) Loom-like fibers would work as well.
27. Compare with Status Quo
val sum =
val f1 = Future(c1.read)
val f2 = Future(c2.read)
for
x <- f1
y <- f2
yield x + y
Composition of futures is monadic
but creation isn’t, which is a bit awkward.
28. A Strawman
lampepfl/async is an early stage prototype of a modern, low-level
concurrency library in direct style.
Main elements
Futures: the primary active elements
Channels: the primary passive elements
Async Sources Futures and Channels both implement a new
fundamental abstraction: an asynchronous source.
Async Contexts An async context is a capability that allows
a computation to suspend while waiting for the result of an
async source.
Link: github.com/lampepfl/async
29. Futures
The Future trait is defined as follows:
trait Future[+T] extends Async.Source[Try[T]], Cancellable:
def result(using Async): Try[T]
def value(using Async): T = result.get
The result method can be defined like this:
def result(using async: Async): T = async.await(this)
async is a capability that allows to suspend in an await method.
30. Futures
The Future trait is defined as follows:
trait Future[+T] extends Async.Source[Try[T]], Cancellable:
def result(using Async): Try[T]
def value(using Async): T = result.get
The result method can be defined like this:
def result(using async: Async): T = async.await(this)
async is a capability that allows to suspend in an await method.
31. Async
The Async trait is defined as follows:
trait Async:
def await[T](src: Async.Source[T]): T
def scheduler: ExecutionContext
def group: CancellationGroup
def withGroup(group: CancellationGroup): Async
await gets the (first) element of an Async.Source.
It suspends if necessary.
32. Async.Source
Futures are a particular kind of an async source. (Other
implementations come from channels).
Async sources are the primary means of communication
between asynchronous computations
They can be composed in interesting ways.
For instance, map and filter are provided:
extension [T](s: Source[T])
def map[U](f: T => U): Source[U]
def filter(p: T => Boolean): Source[T]
33. Async.Source
Futures are a particular kind of an async source. (Other
implementations come from channels).
Async sources are the primary means of communication
between asynchronous computations
They can be composed in interesting ways.
For instance, map and filter are provided:
extension [T](s: Source[T])
def map[U](f: T => U): Source[U]
def filter(p: T => Boolean): Source[T]
34. Races
A race passes on the first of several sources:
def race[T](sources: Source[T]*): Source[T]
Higher-level operation:
def either[T1, T2](src1: Source[T1], src2: Source[T2])
: Source[Either[T, U]] =
race(
src1.map(Left(_)),
src2.map(Right(_))
)
35. Structured Concurrency
It’s now easy to implement zip and alt on futures:
extension [T](f1: Future[T])
def zip[U](f2: Future[U])(using Async): Future[(T, U)] =
Future:
await(either(f1, f2)) match
case Left(Success(x1)) => (x1, f2.value)
case Right(Success(x2)) => (f1.value, x2)
case Left(Failure(ex)) => throw ex
case Right(Failure(ex)) => throw ex
36. Structured Concurrency
It’s now easy to implement zip and alt on futures:
extension [T](f1: Future[T])
def alt(f2: Future[T])(using Async): Future[T] =
Future:
await(either(f1, f2)) match
case Left(Success(x1)) => x1
case Right(Success(x2)) => x2
case Left(_: Failure[?]) => f2.value
case Right(_: Failure[?]) => f1.value
37. Why Futures & Channels?
Futures: The simplest way to get parallelism
Define a computation
Run it in parallel
Await the result when needed
Channels: The canonical way of communication between
computations.
Both are instances as asynchronous sources
38. Why not Coroutines?
Often, coroutines (in the sense of CSP or goroutines) are used
instead of futures to work with channels.
But:
We need to be able to wait for a coroutine’s termination.
We need to handle any exceptions in the coroutine on the
outside
Both are achieved by using a Future[Unit].
So no different abstractions are needed.
39. Why an ErrorType Fixed to Try?
Natural solution if the language supports exception
But common complaint for current futures:
Error type is fixed to be Exception.
This makes it awkward to handle other errors.
For instance, how would you implement this function?
def acrobatics(xs: List[Future[Result[T, E]]])
: Future[Result[List[T], E]] =
40. Why an ErrorType Fixed to Try?
Natural solution if the language supports exception
But common complaint for current futures:
Error type is fixed to be Exception.
This makes it awkward to handle other errors.
For instance, how would you implement this function?
def acrobatics(xs: List[Future[Result[T, E]]])
: Future[Result[List[T], E]] =
41. Why an ErrorType Fixed to Try?
Natural solution if the language supports exception
But common complaint for current futures:
Error type is fixed to be Exception.
This makes it awkward to handle other errors.
For instance, how would you implement this function?
def acrobatics(xs: List[Future[Result[T, E]]])
: Future[Result[List[T], E]] =
42. Why an ErrorType Fixed to Try?
Natural solution if the language supports exception
But common complaint for current futures:
Error type is fixed to be Exception.
This makes it awkward to handle other errors.
New direct style abstractions don’t have that problem anymore!
def acrobatics(xs: List[Future[Result[T, E]]])
: Future[Result[List[T], E]] =
Future:
Result:
xs.map(_.value.?)
Simple compositions, no traverse or lift is needed.
43. Conclusion
Direct style has lots to offer
Suspensions can express every monad, but, provide more flexible
composition.
This gives completely new possibilities to express practical
foundations for concurrency and async I/O.
The future will be interesting…
Thank You
44. Conclusion
Direct style has lots to offer
Suspensions can express every monad, but, provide more flexible
composition.
This gives completely new possibilities to express practical
foundations for concurrency and async I/O.
The future will be interesting…
Thank You