Launch the First Process in Linux SystemJian-Hong Pan
The session: https://coscup.org/2022/en/session/AGCMDJ
After Linux kernel boots, it will try to launch first process “init” in User Space. Then, the system begins the featured journey of the Linux distribution.
This sharing takes Busybox as the example and shows that how does Linux kernel find the “init” which directs to the Busybox. And, what will Busybox do and how to get the console. Try to make it like a simple Linux system.
Before Linux kernel launches “init” process, the file system and storage corresponding drivers/modules must be loaded to find the “init”. Besides, to mount the root file system correctly, the kernel boot command must include the root device and file system format parameters.
On the other hand, the Busybox directed from “init” is a lightweight program, but has rich functions, just like a Swiss Army Knife. So, it is usually used on the simple environment, like embedded Linux system.
This sharing will have a demo on a virtual machine first, then on the Raspberry Pi.
Drafts:
* https://hackmd.io/@starnight/Busbox_as_the_init
* https://hackmd.io/@starnight/Build_Alpines_Root_Filesystem_Bootstrap
Relate idea: https://hackmd.io/@starnight/Systems_init_and_Containers_COMMAND_Dockerfiles_CMD
Multi cluster, multitenant and hierarchical kafka messaging service slideshareAllen (Xiaozhong) Wang
This document discusses Netflix's approach to scaling Apache Kafka through a hierarchical, multi-cluster architecture. It addresses the challenges of scaling a single Kafka cluster, such as increased latency and vulnerability to failures. Netflix uses multiple "fronting" Kafka clusters for data collection and buffering optimized for producers. Consumer clusters scale by adding brokers or moving partitions to new clusters. Producers and consumers can operate across multiple clusters simultaneously using routing services. This multi-cluster approach allows independent scaling of producers and consumers while balancing data distribution.
This document summarizes a presentation on developing with Apache NiFi. It discusses NiFi's REST API for programmatic access, the NiFi developer guide for building custom processors, and tips for contributing to the NiFi project through the GitHub pull request process. Key aspects of the NiFi architecture like its repositories and FlowFile lifecycle are also overviewed.
This document provides information about x86 architecture including registers, flags, modes, common instructions, Intel and AT&T syntax, system calls, examples, and references. It defines the purpose of key registers like EAX, EBX, ESP and flags. It explains real and protect modes and differences between Intel and AT&T syntax. Examples demonstrate how to write assembly code and call system calls. References provided can be used to learn more about x86 assembly programming.
Git is a distributed version control system designed to be efficient, support non-linear development (e.g. branching and merging), and work well on large projects with many developers collaborating simultaneously on the same files. It stores content in a data model of immutable objects (blobs, trees, commits) accessed through references like branches and tags. This allows it to efficiently track file history and versions across branches without duplicating data.
Linux Kernel vs DPDK: HTTP Performance ShowdownScyllaDB
In this session I will use a simple HTTP benchmark to compare the performance of the Linux kernel networking stack with userspace networking powered by DPDK (kernel-bypass).
It is said that kernel-bypass technologies avoid the kernel because it is "slow", but in reality, a lot of the performance advantages that they bring just come from enforcing certain constraints.
As it turns out, many of these constraints can be enforced without bypassing the kernel. If the system is tuned just right, one can achieve performance that approaches kernel-bypass speeds, while still benefiting from the kernel's battle-tested compatibility, and rich ecosystem of tools.
I have tried my best to describe Samba Server through this PPT. I hope you guys will love this and this ppt will be helpful for you all.
Thanks,
Veeral Arora
Launch the First Process in Linux SystemJian-Hong Pan
The session: https://coscup.org/2022/en/session/AGCMDJ
After Linux kernel boots, it will try to launch first process “init” in User Space. Then, the system begins the featured journey of the Linux distribution.
This sharing takes Busybox as the example and shows that how does Linux kernel find the “init” which directs to the Busybox. And, what will Busybox do and how to get the console. Try to make it like a simple Linux system.
Before Linux kernel launches “init” process, the file system and storage corresponding drivers/modules must be loaded to find the “init”. Besides, to mount the root file system correctly, the kernel boot command must include the root device and file system format parameters.
On the other hand, the Busybox directed from “init” is a lightweight program, but has rich functions, just like a Swiss Army Knife. So, it is usually used on the simple environment, like embedded Linux system.
This sharing will have a demo on a virtual machine first, then on the Raspberry Pi.
Drafts:
* https://hackmd.io/@starnight/Busbox_as_the_init
* https://hackmd.io/@starnight/Build_Alpines_Root_Filesystem_Bootstrap
Relate idea: https://hackmd.io/@starnight/Systems_init_and_Containers_COMMAND_Dockerfiles_CMD
Multi cluster, multitenant and hierarchical kafka messaging service slideshareAllen (Xiaozhong) Wang
This document discusses Netflix's approach to scaling Apache Kafka through a hierarchical, multi-cluster architecture. It addresses the challenges of scaling a single Kafka cluster, such as increased latency and vulnerability to failures. Netflix uses multiple "fronting" Kafka clusters for data collection and buffering optimized for producers. Consumer clusters scale by adding brokers or moving partitions to new clusters. Producers and consumers can operate across multiple clusters simultaneously using routing services. This multi-cluster approach allows independent scaling of producers and consumers while balancing data distribution.
This document summarizes a presentation on developing with Apache NiFi. It discusses NiFi's REST API for programmatic access, the NiFi developer guide for building custom processors, and tips for contributing to the NiFi project through the GitHub pull request process. Key aspects of the NiFi architecture like its repositories and FlowFile lifecycle are also overviewed.
This document provides information about x86 architecture including registers, flags, modes, common instructions, Intel and AT&T syntax, system calls, examples, and references. It defines the purpose of key registers like EAX, EBX, ESP and flags. It explains real and protect modes and differences between Intel and AT&T syntax. Examples demonstrate how to write assembly code and call system calls. References provided can be used to learn more about x86 assembly programming.
Git is a distributed version control system designed to be efficient, support non-linear development (e.g. branching and merging), and work well on large projects with many developers collaborating simultaneously on the same files. It stores content in a data model of immutable objects (blobs, trees, commits) accessed through references like branches and tags. This allows it to efficiently track file history and versions across branches without duplicating data.
Linux Kernel vs DPDK: HTTP Performance ShowdownScyllaDB
In this session I will use a simple HTTP benchmark to compare the performance of the Linux kernel networking stack with userspace networking powered by DPDK (kernel-bypass).
It is said that kernel-bypass technologies avoid the kernel because it is "slow", but in reality, a lot of the performance advantages that they bring just come from enforcing certain constraints.
As it turns out, many of these constraints can be enforced without bypassing the kernel. If the system is tuned just right, one can achieve performance that approaches kernel-bypass speeds, while still benefiting from the kernel's battle-tested compatibility, and rich ecosystem of tools.
I have tried my best to describe Samba Server through this PPT. I hope you guys will love this and this ppt will be helpful for you all.
Thanks,
Veeral Arora
Hands-on-Lab (TP) sur l'utilisation de Git en mode avancé dispensé avec mes collègues Alexis DMYTRYK et Thomas COLLIGNON lors de DevoxxFR 2018.
Présentation disponible ici : https://fr.slideshare.net/JrmeTAMBORINI/tp-git-avanc-devoxxfr-2018-pres
Virtual Flink Forward 2020: A deep dive into Flink SQL - Jark WuFlink Forward
During last two major versions (1.9 & 1.10), Apache Flink community spent lots of effort to improve the architecture for further unified batch & streaming processing. One example for that is Flink SQL added the ability to support multiple SQL planners under the same API. This talk will first discuss the motivation behind these movements, but more importantly will have a deep dive into Flink SQL. The presentation shows the unified architecture to handle streaming and batch queries and explain how Flink translates queries into the relational expressions, leverages Apache Calcite to optimize them, and generates efficient runtime code for execution. Besides, this talk will also describe the lifetime of a query in detail, how optimizer improve the plan based on relational node patterns, how Flink leverages binary data format for its basic data structure, and how does certain operator works. This would give audience better understanding of Flink SQL internals.
Introduction to Git/Github - A beginner's guideRohit Arora
Introduction to Git/Github - A beginner's guide
Agenda:
Installing Git
Introduction to Version Control
Git Basics
Creating a new local Git repository
Cloning a Git repository
Making use of Git commit history
Reverting files to previous states
Creating a Github Repository
Adding, Committing & Pushing changes
Branching
Merging Branches
Sending Pull Requests
Conflict Resolution
and 3 Exercises
The document discusses configuring scheduled reports in Zabbix. It describes installing and configuring the Zabbix web service to generate scheduled reports. It also covers configuring the Zabbix server to enable report writers and specify the web service URL. Additionally, it discusses creating dashboards, items, and scheduled reports in the Zabbix frontend and testing the scheduled reports.
This document provides an introduction to Apache Flink. It begins with an overview of the presenters and structure of the presentation. It then discusses Flink's APIs, architecture, and execution model. Key concepts are explained like streaming vs batch processing, scaling, the job manager and task managers. It provides a demo of Flink's DataSet API for batch processing and explains a WordCount example program. The goal is to get attendees started with Apache Flink.
Virtual File System in Linux Kernel
Note: When you view the the slide deck via web browser, the screenshots may be blurred. You can download and view them offline (Screenshots are clear).
Booting Android: bootloaders, fastboot and boot imagesChris Simmonds
This document discusses booting Android devices. It covers Android boot images, bootloaders, fastboot protocol, and file systems used for different types of flash memory in Android devices. The key topics covered include bootloaders loading the boot and recovery images, the fastboot protocol for flashing and debugging, and file systems like ext4, f2fs, yaffs2 used on different flash chips like eMMC, SD cards, and raw NAND flash.
This document provides an overview of version control systems and compares Git and SVN. It discusses why version control is useful, describes popular version control systems from the past and present, and highlights key differences between distributed (Git) and centralized (SVN) systems. The document also includes instructions for downloading, setting up, and using basic Git functions for managing a code repository, including commands for saving changes, inspecting history, undoing edits, syncing repositories, and working with branches.
LVM (Logical Volume Manager) allows managing disks in a different way by creating virtual disks called logical volumes from physical partitions. It does not have the same limitations as physical disks. LVM concepts include physical volumes representing physical partitions, volume groups which act as virtual disks by combining multiple physical volumes, and logical volumes which are partitions within volume groups that can be resized and moved independently of physical storage. LVM provides flexibility in managing storage and can be used with other technologies like encryption and RAID.
Cloudflare uses ClickHouse to analyze over 1 million DNS queries per second from its global network. ClickHouse is a column-oriented database that allows Cloudflare to perform complex ad-hoc queries and aggregations over trillions of rows of DNS log data with dimensions like timestamp, zone, and location. They store raw logs for 3 months and aggregated data indefinitely to monitor trends and traffic over time. The multi-tenant ClickHouse cluster at Cloudflare inserts over 8 million rows per second and has excellent query performance for common aggregations used in their analytics.
The document discusses toolchains and cross toolchains. It defines a toolchain as a collection of tools including a C compiler, C libraries, and binary utilities. A cross toolchain is a toolchain configured to compile code for a platform other than the one on which the toolchain is running. The document outlines steps for building a cross toolchain, including obtaining kernel headers, building binary utilities, compilers, and libraries. It also discusses automated build tools like Crosstool and testing the generated cross toolchain.
Introducing BinarySortedMultiMap - A new Flink state primitive to boost your ...Flink Forward
Flink Forward San Francisco 2022.
Probably everyone who has written stateful Apache Flink applications has used one of the fault-tolerant keyed state primitives ValueState, ListState, and MapState. With RocksDB, however, retrieving and updating items comes at an increased cost that you should be aware of. Sometimes, these may not be avoidable with the current API, e.g., for efficient event-time stream-sorting or streaming joins where you need to iterate one or two buffered streams in the right order. With FLIP-220, we are introducing a new state primitive: BinarySortedMultiMapState. This new form of state offers you to (a) efficiently store lists of values for a user-provided key, and (b) iterate keyed state in a well-defined sort order. Both features can be backed efficiently by RocksDB with a 2x performance improvement over the current workarounds. This talk will go into the details of the new API and its implementation, present how to use it in your application, and talk about the process of getting it into Flink.
by
Nico Kruber
Note: When you view the the slide deck via web browser, the screenshots may be blurred. You can download and view them offline (Screenshots are clear).
The document describes the GCC Link Time Optimization (LTO) compilation process. It shows how GCC and the linker communicate via a transfer vector in the liblto_plugin.so library. GCC generates LTO objects and passes symbol information to the linker. The lto-wrapper driver then performs the LTO and code generation steps, outputting new object files for the linker to incorporate into the final executable.
The document discusses ioremap and mmap functions in Linux for mapping physical addresses into the virtual address space. Ioremap is used when physical addresses are larger than the virtual address space size. It maps physical addresses to virtual addresses that can be accessed by the CPU. Mmap allows a process to map pages of a file into virtual memory. It is useful for reducing memory copies and improving performance of file read/write operations. The document outlines the functions, flags, and flows of ioremap, mmap, and implementing a custom mmap file operation for direct physical memory mapping.
This document discusses the Android multimedia framework on Jelly Bean. It provides an introduction to OpenMAX and describes the simple stack architecture including the developer API, event handler, surface holder, StageFright, OpenMAX interface, and software/hardware codecs. It explains the workflows and sequence flows for playing a media file, including setting the data source, preparing to play, and starting playback. Finally, it covers the synchronization architecture and flow of StageFright.
Graph Gurus Episode 11: Accumulators for Complex Graph AnalyticsTigerGraph
This document discusses using accumulators in GSQL for complex graph analytics. Accumulators allow for parallel aggregation of data across nodes in a graph. Different types of accumulators like sum, max, min, and average accumulators are described. Examples provided include counting movies seen by friends and calculating PageRank across a graph. Accumulators support parallel processing by multiple workers and efficient consolidation of results.
GraalVM is a high-performance runtime for dynamic, static, and native languages. GraalVM supports Java, Scala, Kotlin, Groovy, and other JVM-based languages. At the same time, it can run the dynamic scripting languages JavaScript including node.js, Ruby, R, and Python. In this session we'll talk about the performance boost you can get from running your code on GraalVM, look at the examples of running typical web-applications with it, enhancing them with code in other languages, creating native images for incredibly fast startup and low memory overhead for your services. GraalVM offers you the opportunity to write the code in the language you want, and run the resulting program really fast.
This document introduces functional programming concepts like functors, applicatives, and monads in Scala. It defines type classes like Functor, Applicative, and Monad to capture these concepts. Implementations for Option and List are provided as examples. Laws are discussed to ensure type class instances behave as expected. The Cats library is introduced as providing pre-defined type classes and instances that can be used instead of rolling your own.
Hands-on-Lab (TP) sur l'utilisation de Git en mode avancé dispensé avec mes collègues Alexis DMYTRYK et Thomas COLLIGNON lors de DevoxxFR 2018.
Présentation disponible ici : https://fr.slideshare.net/JrmeTAMBORINI/tp-git-avanc-devoxxfr-2018-pres
Virtual Flink Forward 2020: A deep dive into Flink SQL - Jark WuFlink Forward
During last two major versions (1.9 & 1.10), Apache Flink community spent lots of effort to improve the architecture for further unified batch & streaming processing. One example for that is Flink SQL added the ability to support multiple SQL planners under the same API. This talk will first discuss the motivation behind these movements, but more importantly will have a deep dive into Flink SQL. The presentation shows the unified architecture to handle streaming and batch queries and explain how Flink translates queries into the relational expressions, leverages Apache Calcite to optimize them, and generates efficient runtime code for execution. Besides, this talk will also describe the lifetime of a query in detail, how optimizer improve the plan based on relational node patterns, how Flink leverages binary data format for its basic data structure, and how does certain operator works. This would give audience better understanding of Flink SQL internals.
Introduction to Git/Github - A beginner's guideRohit Arora
Introduction to Git/Github - A beginner's guide
Agenda:
Installing Git
Introduction to Version Control
Git Basics
Creating a new local Git repository
Cloning a Git repository
Making use of Git commit history
Reverting files to previous states
Creating a Github Repository
Adding, Committing & Pushing changes
Branching
Merging Branches
Sending Pull Requests
Conflict Resolution
and 3 Exercises
The document discusses configuring scheduled reports in Zabbix. It describes installing and configuring the Zabbix web service to generate scheduled reports. It also covers configuring the Zabbix server to enable report writers and specify the web service URL. Additionally, it discusses creating dashboards, items, and scheduled reports in the Zabbix frontend and testing the scheduled reports.
This document provides an introduction to Apache Flink. It begins with an overview of the presenters and structure of the presentation. It then discusses Flink's APIs, architecture, and execution model. Key concepts are explained like streaming vs batch processing, scaling, the job manager and task managers. It provides a demo of Flink's DataSet API for batch processing and explains a WordCount example program. The goal is to get attendees started with Apache Flink.
Virtual File System in Linux Kernel
Note: When you view the the slide deck via web browser, the screenshots may be blurred. You can download and view them offline (Screenshots are clear).
Booting Android: bootloaders, fastboot and boot imagesChris Simmonds
This document discusses booting Android devices. It covers Android boot images, bootloaders, fastboot protocol, and file systems used for different types of flash memory in Android devices. The key topics covered include bootloaders loading the boot and recovery images, the fastboot protocol for flashing and debugging, and file systems like ext4, f2fs, yaffs2 used on different flash chips like eMMC, SD cards, and raw NAND flash.
This document provides an overview of version control systems and compares Git and SVN. It discusses why version control is useful, describes popular version control systems from the past and present, and highlights key differences between distributed (Git) and centralized (SVN) systems. The document also includes instructions for downloading, setting up, and using basic Git functions for managing a code repository, including commands for saving changes, inspecting history, undoing edits, syncing repositories, and working with branches.
LVM (Logical Volume Manager) allows managing disks in a different way by creating virtual disks called logical volumes from physical partitions. It does not have the same limitations as physical disks. LVM concepts include physical volumes representing physical partitions, volume groups which act as virtual disks by combining multiple physical volumes, and logical volumes which are partitions within volume groups that can be resized and moved independently of physical storage. LVM provides flexibility in managing storage and can be used with other technologies like encryption and RAID.
Cloudflare uses ClickHouse to analyze over 1 million DNS queries per second from its global network. ClickHouse is a column-oriented database that allows Cloudflare to perform complex ad-hoc queries and aggregations over trillions of rows of DNS log data with dimensions like timestamp, zone, and location. They store raw logs for 3 months and aggregated data indefinitely to monitor trends and traffic over time. The multi-tenant ClickHouse cluster at Cloudflare inserts over 8 million rows per second and has excellent query performance for common aggregations used in their analytics.
The document discusses toolchains and cross toolchains. It defines a toolchain as a collection of tools including a C compiler, C libraries, and binary utilities. A cross toolchain is a toolchain configured to compile code for a platform other than the one on which the toolchain is running. The document outlines steps for building a cross toolchain, including obtaining kernel headers, building binary utilities, compilers, and libraries. It also discusses automated build tools like Crosstool and testing the generated cross toolchain.
Introducing BinarySortedMultiMap - A new Flink state primitive to boost your ...Flink Forward
Flink Forward San Francisco 2022.
Probably everyone who has written stateful Apache Flink applications has used one of the fault-tolerant keyed state primitives ValueState, ListState, and MapState. With RocksDB, however, retrieving and updating items comes at an increased cost that you should be aware of. Sometimes, these may not be avoidable with the current API, e.g., for efficient event-time stream-sorting or streaming joins where you need to iterate one or two buffered streams in the right order. With FLIP-220, we are introducing a new state primitive: BinarySortedMultiMapState. This new form of state offers you to (a) efficiently store lists of values for a user-provided key, and (b) iterate keyed state in a well-defined sort order. Both features can be backed efficiently by RocksDB with a 2x performance improvement over the current workarounds. This talk will go into the details of the new API and its implementation, present how to use it in your application, and talk about the process of getting it into Flink.
by
Nico Kruber
Note: When you view the the slide deck via web browser, the screenshots may be blurred. You can download and view them offline (Screenshots are clear).
The document describes the GCC Link Time Optimization (LTO) compilation process. It shows how GCC and the linker communicate via a transfer vector in the liblto_plugin.so library. GCC generates LTO objects and passes symbol information to the linker. The lto-wrapper driver then performs the LTO and code generation steps, outputting new object files for the linker to incorporate into the final executable.
The document discusses ioremap and mmap functions in Linux for mapping physical addresses into the virtual address space. Ioremap is used when physical addresses are larger than the virtual address space size. It maps physical addresses to virtual addresses that can be accessed by the CPU. Mmap allows a process to map pages of a file into virtual memory. It is useful for reducing memory copies and improving performance of file read/write operations. The document outlines the functions, flags, and flows of ioremap, mmap, and implementing a custom mmap file operation for direct physical memory mapping.
This document discusses the Android multimedia framework on Jelly Bean. It provides an introduction to OpenMAX and describes the simple stack architecture including the developer API, event handler, surface holder, StageFright, OpenMAX interface, and software/hardware codecs. It explains the workflows and sequence flows for playing a media file, including setting the data source, preparing to play, and starting playback. Finally, it covers the synchronization architecture and flow of StageFright.
Graph Gurus Episode 11: Accumulators for Complex Graph AnalyticsTigerGraph
This document discusses using accumulators in GSQL for complex graph analytics. Accumulators allow for parallel aggregation of data across nodes in a graph. Different types of accumulators like sum, max, min, and average accumulators are described. Examples provided include counting movies seen by friends and calculating PageRank across a graph. Accumulators support parallel processing by multiple workers and efficient consolidation of results.
GraalVM is a high-performance runtime for dynamic, static, and native languages. GraalVM supports Java, Scala, Kotlin, Groovy, and other JVM-based languages. At the same time, it can run the dynamic scripting languages JavaScript including node.js, Ruby, R, and Python. In this session we'll talk about the performance boost you can get from running your code on GraalVM, look at the examples of running typical web-applications with it, enhancing them with code in other languages, creating native images for incredibly fast startup and low memory overhead for your services. GraalVM offers you the opportunity to write the code in the language you want, and run the resulting program really fast.
This document introduces functional programming concepts like functors, applicatives, and monads in Scala. It defines type classes like Functor, Applicative, and Monad to capture these concepts. Implementations for Option and List are provided as examples. Laws are discussed to ensure type class instances behave as expected. The Cats library is introduced as providing pre-defined type classes and instances that can be used instead of rolling your own.
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.
A reworking of my 2010 RubyConf lightning talk introducing Go via a concurrent implementation of MapReduce. This code is probably buggy as hell and the design awful but it's also a reasonably good intro to the full breadth of Go.
Découverte d'algèbre, d'interpréteur par la création d'un DSL pour la base de données Aerospike. Le tout est implémenté dans le langage Scala avec un style fonctionnel.
1. The document discusses using Scala for concurrent application development with Futures and Reactive Extensions (Rx). It provides examples of asynchronous programming using Futures, working with Observables in Rx, composing asynchronous operations, and handling errors.
2. Key concepts covered include Futures, Promises, Try monad, Observables, combining asynchronous operations, error handling, cold vs hot Observables, and concurrency control.
3. Examples demonstrate basic usage of Futures and Observables, composing operations, handling errors, working with Observable sequences, and monitoring file changes reactively.
Generic Functional Programming with Type ClassesTapio Rautonen
What it takes to build type assisted domain specific languages in Scala? Introducing the concepts of type classes, functional programming and generic algebra.
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
Free Monads are a powerful technique that can separate the representation of programs from the messy details of how they get run.
I'll go into the details of how they work, how to use them for fun and profit in your own code, and demonstrate a live Free Monad-driven tank game.
Supporting code at https://github.com/kenbot/free
Introduction to how to test our programs using imperative programming and functional programming with Tagless Final technique and how to make it simpler using ZIO. ZIO provides many features for concurrency and asynchronous programs. This presentation is about how to use ZIO environment to test your application.
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.
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.
This document provides an introduction to monads through a presentation given by Mikhail Girkin. Some key points:
1. Monads are commonly used in functional programming to represent computations or chaining of operations. They consist of a type, a unit operation, and a bind (flatMap) operation.
2. Many languages like C# and Java already use monads through things like flatMap, they just don't refer to them as monads. Collections like Seq are monads.
3. Option and Try are examples of monads used to handle potential failures gracefully. For-comprehensions provide a cleaner way to write code involving monads compared to nested flatMaps.
4. Other
Machine-level Composition of Modularized Crosscutting Concernssaintiss
The document discusses different approaches to modularizing crosscutting concerns in software, including object-oriented programming (j), inter-type declarations (ij), aspect-oriented programming using pointcuts and advice (aj), and context-oriented programming (cj). It proposes a dedicated machine model based on objects and delegation as a core mechanism to support modularization at the machine level.
This document discusses monads and continuations in functional programming. It provides examples of using monads like Option and List to handle failure in sequences of operations. It also discusses delimited continuations as a low-level control flow primitive that can implement exceptions, concurrency, and suspensions. The document proposes using monads to pass implicit state through programs by wrapping computations in a state transformer (ST) monad.
The Essence of the Iterator pattern treats iterating over collections as two problems, which exhibit traversal of collections (and modifying the content) and accumulating values based on the contents. Jeremy Gibbons and Bruno C.d.S. Oliveira show how Applicative Functors and related type classes can be used in functional programming to solve these problems.
Paper: http://www.cs.ox.ac.uk/jeremy.gibbons/publications/iterator.pdf
The paper "Essence of the iterator pattern" is widely quoted amongst the functional programming community and illustrates nicely how recent acadamic research (Applicative Functors, McBride, 2008) finds its way into language design and application of functional programming languages such as Scala or Haskell.
The slides give a brief introduction and were presented at the "Papers We Love" Meetup in Hamburg.
The document discusses reinventing the free monad to model effects in different ways, including with pure effects, effects with returns, and simpler effects using bind. It also covers composing effects, type-safe mocking, runtime optimization, aspect-oriented programming, and hacking the free monad to add capabilities like parallelism, failure handling, and nondeterminism. However, it notes that excessively hacking the free monad can lead to poor composability and performance due to deeply nested types, and can blur the distinction between effects and machinery.
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.
Asynchronous programming with java script and node.jsTimur Shemsedinov
The document discusses asynchronous programming techniques in JavaScript including callbacks, promises, async/await, and libraries like async.js. It covers problems with nesting and different contracts. It then introduces the Metasync library which aims to simplify asynchronous code through functional composition and abstractions like collectors, queues, and throttling. Metasync uses an error-back compatible contract and allows both sequential and parallel asynchronous flows.
Testing in the World of Functional ProgrammingLuka Jacobowitz
This document summarizes a presentation about testing in functional programming. It discusses:
1. Property-based testing and how it can find bugs early by generating many test cases, including edge cases. However, it can be painful to write tests for complex functions interacting with external systems.
2. Mocking external dependencies to test internal logic, made possible through techniques like tagless final which separate interfaces from implementations. Complex interactions can be modeled with state machines.
3. Other FP testing techniques like newtypes, refined types, and libraries that make testing easier by restricting valid inputs. The presentation provides examples of testing parsing, network calls and database access in isolation.
Similar to Embedding Generic Monadic Transformer into Scala. [Tfp2022] (20)
This document discusses Scala 3's support for asynchronous programming using async/await. It begins with reminders about monadic effects and reactivity using effect monads. It then discusses how async/await improves on effect monads by avoiding manual coloring and reducing the number of awaits needed. The document describes how automatic coloring can be achieved using a macro. It also discusses challenges around monad interoperability and optimization of the monadic continuation passing style transformation.
This document discusses behavior modeling using behavior algebra and Akka actors. It provides an example of modeling a coffee machine as a behavior using behavior algebra equations and then implementing it in Scala with Akka actors. Key points covered include:
- Defining behaviors as labeled transition systems (LTS) with states, actions, and transitions between states via actions
- Composing behaviors using operations like sequential composition, choice composition, and recursion to build larger behaviors from smaller ones
- Modeling a basic coffee machine as a behavior that can accept coins and button presses and dispense coffee
- Expanding the model to add features like accumulating credit from multiple coins and disabling/enabling the machine
- Implementing the coffee machine
Papers We Love / Kyiv : PAXOS (and little about other consensuses )Ruslan Shevchenko
Slides from talk on 'Papers we Love, Kyiv' meetup: 27.07.2018 -- description of Paxos algorithm and friends.
https://www.meetup.com/Papers-We-Love-Kyiv/events/252974063/
This document discusses factors that influence the evolution and adoption of programming languages like Scala. It argues that for a language to be evolutionarily stable, it needs to survive, be adopted by a user base that is more than 1%, and be attractive. Scala's main value proposition is its support for static metaprogramming, but it needs to improve concurrency support, reduce boilerplate code, and simplify its core to lower the learning curve. New developments like Dotty and Squid could help address current issues and support further language evolution.
The document discusses functions and the Liskov substitution principle. It defines functions with signatures like f: A => B, meaning a function f that takes an input of type A and returns an output of type B. It explains function composition using andThen and |>. It also discusses how the Liskov substitution principle states that if S is a subtype of T, then objects of type T may be replaced with objects of type S without altering any desirable properties of that program. This allows subclasses to substitute behavior while preserving contracts with external consumers.
This document discusses various streaming approaches and implementations in different programming languages and frameworks. It covers:
1) Notable streaming implementations like SISAL, Occam, Inferno, Limbo, Go, Orc, and their origins.
2) Scala implementations of streaming including iteratee/enumeratee, scalaz-streams, fs2, akka-streams, gopher, monix.io.
3) Core concepts of streaming including pull-based and push-based approaches, active channels, and how different frameworks implement these concepts using combinators and domain-specific languages.
This document discusses the evolution of programming languages and hardware over time. It covers older languages like FORTRAN, BASIC, and C/C++. It also discusses newer languages like Rust, Go, and Julia. It describes how memory management, concurrency models, and distributed computing have changed. It proposes using techniques like functional interpreters and macros to allow languages to be more easily extended and adapted to new hardware. The document advocates for approaches that can efficiently support both old and new programming ideas.
This document discusses various techniques for working with types in Scala, including:
1. The main alternatives for Scala types including classical OO, algebraic, generic, and structured types. It recommends choosing styles based on use cases and setting guidelines.
2. The differences between run-time and compile-time dispatch and how they are implemented in Scala.
3. Techniques for working with types including tagged types, type aliases, and implicit evidence to provide different behaviors based on types known at compile-time.
4. Resources for learning more about advanced type-level programming in Scala, particularly the Shapeless library.
Why scala is not my ideal language and what I can do with thisRuslan Shevchenko
- The document discusses some of the author's criticisms of Scala, including its use of implicit parameters to configure runtime behavior, and lack of good support for asynchronous programming.
- The author proposes some workarounds, like annotating imports to avoid implicit conflicts, and patching the compiler to add more information to Future exceptions. However, the ideal solution would be language changes or improvements to asynchronous abstractions like Async.
- Overall, the author argues that Scala is not ideal for some use cases like asynchronous programming, but provides some workarounds people can use in the meantime. The best solutions require changes to the language and standard library.
This document provides a dictionary of scala programming concepts including definitions of common jargon like ADT, typeclasses, extension methods, and call-by semantics. It defines ADT as algebraic data types, which were introduced in languages like Algol 60 and ML, and pattern matching which allows decomposing ADT values. Typeclasses are defined as rules for types like equality, with instances providing implementations. Extension methods and implicit conversions add methods to types via implicit parameters. Call-by-name and call-by-need semantics are discussed in relation to lazy evaluation.
This document discusses programming techniques for low-latency Java applications. It begins by explaining what low-latency means and when it is needed. It then covers various techniques including: using concurrent flows and minimizing context switches; exchanging data between threads via queues instead of shared memory; preallocating objects to avoid allocations; and directly accessing serialized data instead of object instances. The document also discusses memory issues like garbage collection pauses and cache line contention. It covers alternatives for accessing native code like JNA, JNI, and shared memory. Critical JNI is presented as a faster option than regular JNI.
This document outlines a presentation about CSP (Communicating Sequential Processes) theory and implementation in Scala using the scala-gopher library. It begins with an introduction to CSP theory, history, and languages like Occam and Limbo that were influenced by it. It then demonstrates how scala-gopher implements key CSP concepts like channels, selectors, and processes in Scala. Examples are shown of writing Fibonacci sequences and broadcasting messages using these primitives. Potential issues with the current scala-gopher implementation are noted.
This document discusses various techniques for integrating R with other programming languages and ecosystems. It begins by asking what to do after building a model in R, such as rewriting the code, integrating R with other languages, or implementing business logic directly in R. The document then covers options for integrating R at the command line, library level, and for calling R from other languages like C++. It also discusses using R for web applications via techniques like rApache, shiny, and openCPU. In the end it argues that R can be effectively used as part of an application infrastructure along with software engineering languages.
The document reviews JavaScript languages that can be compiled to JavaScript, including CoffeeScript, Dart, TypeScript, Traceur, Emscripten, Scala.js, ClojureScript, Kotlin, and others. It discusses their features like static typing, classes, async/await support, and ability to port other language ecosystems to run in the browser. It also covers architectures like Opa and Ur/Web that aim to use a single language across front-end, back-end, and databases.
The document discusses domain modeling approaches in a post-object-oriented world. It outlines issues with traditional OO domain modeling and proposes an alternative approach. This involves:
1. Describing a limited set of domain objects and relationships as an "algebra" rather than a universal ontology.
2. Using existential equality where identity is defined by attributes rather than identity.
3. Building a simple domain model for a toy billing system to demonstrate the approach.
4. Discussing how the domain model can be implemented and improved, including handling errors, deaggregating components, and using internal domain-specific languages.
scala-gopher: async implementation of CSP for scalaRuslan Shevchenko
This document describes scala-gopher, a Scala library that implements Communicating Sequential Processes (CSP) concepts like Go channels. It allows asynchronous programming using constructs like select.forever that handle input/output between channels. The library builds on Akka and SIP 22 for asynchrony. It includes channels, transputers that connect via ports, and replication capabilities for running processes in parallel. The goal is to provide CSP functionality within the Scala ecosystem as a complementary approach to streams and actors.
Programming Languages: some news for the last N yearsRuslan Shevchenko
This document discusses programming languages and their evolution. It covers topics like syntax, type systems, dependent types, and effects tracking. It suggests that while new academic ideas in programming languages take over a decade on average to see wider adoption, trends in industry include integrating other paradigms into mainstream languages and replacing C++ with alternatives like D or Rust. The document also questions what new academic or open source ideas may become part of industry programming in the future.
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
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/
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxrickgrimesss22
Discover the essential features to incorporate in your Winzo clone app to boost business growth, enhance user engagement, and drive revenue. Learn how to create a compelling gaming experience that stands out in the competitive market.
What is Augmented Reality Image Trackingpavan998932
Augmented Reality (AR) Image Tracking is a technology that enables AR applications to recognize and track images in the real world, overlaying digital content onto them. This enhances the user's interaction with their environment by providing additional information and interactive elements directly tied to physical images.
Utilocate offers a comprehensive solution for locate ticket management by automating and streamlining the entire process. By integrating with Geospatial Information Systems (GIS), it provides accurate mapping and visualization of utility locations, enhancing decision-making and reducing the risk of errors. The system's advanced data analytics tools help identify trends, predict potential issues, and optimize resource allocation, making the locate ticket management process smarter and more efficient. Additionally, automated ticket management ensures consistency and reduces human error, while real-time notifications keep all relevant personnel informed and ready to respond promptly.
The system's ability to streamline workflows and automate ticket routing significantly reduces the time taken to process each ticket, making the process faster and more efficient. Mobile access allows field technicians to update ticket information on the go, ensuring that the latest information is always available and accelerating the locate process. Overall, Utilocate not only enhances the efficiency and accuracy of locate ticket management but also improves safety by minimizing the risk of utility damage through precise and timely locates.
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.
Mobile App Development Company In Noida | Drona InfotechDrona Infotech
Looking for a reliable mobile app development company in Noida? Look no further than Drona Infotech. We specialize in creating customized apps for your business needs.
Visit Us For : https://www.dronainfotech.com/mobile-application-development/
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Crescat
Crescat is industry-trusted event management software, built by event professionals for event professionals. Founded in 2017, we have three key products tailored for the live event industry.
Crescat Event for concert promoters and event agencies. Crescat Venue for music venues, conference centers, wedding venues, concert halls and more. And Crescat Festival for festivals, conferences and complex events.
With a wide range of popular features such as event scheduling, shift management, volunteer and crew coordination, artist booking and much more, Crescat is designed for customisation and ease-of-use.
Over 125,000 events have been planned in Crescat and with hundreds of customers of all shapes and sizes, from boutique event agencies through to international concert promoters, Crescat is rigged for success. What's more, we highly value feedback from our users and we are constantly improving our software with updates, new features and improvements.
If you plan events, run a venue or produce festivals and you're looking for ways to make your life easier, then we have a solution for you. Try our software for free or schedule a no-obligation demo with one of our product specialists today at crescat.io
May Marketo Masterclass, London MUG May 22 2024.pdfAdele Miller
Can't make Adobe Summit in Vegas? No sweat because the EMEA Marketo Engage Champions are coming to London to share their Summit sessions, insights and more!
This is a MUG with a twist you don't want to miss.
DDS Security Version 1.2 was adopted in 2024. This revision strengthens support for long runnings systems adding new cryptographic algorithms, certificate revocation, and hardness against DoS attacks.
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
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeAftab Hussain
Understanding variable roles in code has been found to be helpful by students
in learning programming -- could variable roles help deep neural models in
performing coding tasks? We do an exploratory study.
- These are slides of the talk given at InteNSE'23: The 1st International Workshop on Interpretability and Robustness in Neural Software Engineering, co-located with the 45th International Conference on Software Engineering, ICSE 2023, Melbourne Australia
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Łukasz Chruściel
No one wants their application to drag like a car stuck in the slow lane! Yet it’s all too common to encounter bumpy, pothole-filled solutions that slow the speed of any application. Symfony apps are not an exception.
In this talk, I will take you for a spin around the performance racetrack. We’ll explore common pitfalls - those hidden potholes on your application that can cause unexpected slowdowns. Learn how to spot these performance bumps early, and more importantly, how to navigate around them to keep your application running at top speed.
We will focus in particular on tuning your engine at the application level, making the right adjustments to ensure that your system responds like a well-oiled, high-performance race car.
Artificia Intellicence and XPath Extension FunctionsOctavian Nadolu
The purpose of this presentation is to provide an overview of how you can use AI from XSLT, XQuery, Schematron, or XML Refactoring operations, the potential benefits of using AI, and some of the challenges we face.
Artificia Intellicence and XPath Extension Functions
Embedding Generic Monadic Transformer into Scala. [Tfp2022]
1. Ruslan Shevchenko, Kyiv, Ukraine.
<ruslan@shevchenko.kiev.ua>
proofspace.id
Embedding Generic Monadic Transformer into Scala.
{Can we return concurrent programming into mainstream? }
https://github.com/rssh/dotty-cps-async
2. Asynchronous control flow - Scala industrial usage.
for{
r1 <- cacheService.get(id) match
case Some(v) => IO.success(v)
case None => talkToServer(id).map{v =>
cacheService.update(id,v)
v
}
r2 <- talkToServer(r1.data)
result <- if (r2.isOk) then {
writeToFile(resultData) >>=
IO.println("done") >>=
true
} else {
IO.println("abort") >>=
false
}
} yield result
Monadic DSL on top of some effect system or. Future
3. Asynchronous control flow - Scala industrial usage.
for{
r1 <- cacheService.get(id) match
case Some(v) => IO.success(v)
case None => talkToServer(id).map{v =>
cacheService.update(id,v)
v
}
R2 <- talkToServer(r1.data)
result <- if (r2.isOk) then {
writeToFile(r1.data) >>=
IO.println("done") >>=
true
} else {
IO.println("abort") >>=
false
}
} yield result
Monadic DSL on top of some effect system or. Future
async[IO] {
val r1 = cacheService.getOrUpdate(id,
await(talkToServer(id)))
val r2 = talkToServer(r1.data)
if (r2.isOk) then
writeToFile(r1.data)
IO.println("done")
true
else
IO.println("abort")
false
}
"Mainstream" Control-Flow
over some effect system or Future
4. API (simpli
fi
ed)
Well-known async/await interface.
+ - generic monad
- ability to use higher-order functions without runtime support for continuations.
- automatic colouring (awaits can-be omitted if can be restored from the context)
def async[F[_]](f: T):F[T]
def await[F[_]](f: F[T]):T
5. transparent inline
def async[F[_]](using am: CpsMonad[F])[T](inline f: am.Context ?=> T):F[T]
API (simpli
fi
ed)
@compileTimeOnly("await should be inside async block")
def await[G[_],T,F[_]](f: G[T])(using CpsMonadConversion[G,F], CpsMonadContext[F]):
//in real signature here is temporary class, to allow currying of type parameters
def async[F[_]](f: T):F[T]
def await[F[_]](f: F[T]):T
6. transparent inline
def async[F[_]](using am: CpsMonad[F])[T](inline f: am.Context ?=> T):F[T]
API (simpli
fi
ed)
@compileTimeOnly("await should be inside async block")
def await[G[_],T,F[_]](f: G[T])(using CpsMonadConversion[G,F], CpsMonadContext[F]): T
Macro, evaluated during typing
7. transparent inline
def async[F[_]](using am: CpsMonad[F])[T](inline f: am.Context ?=> T):F[T]
API (simpli
fi
ed)
@compileTimeOnly("await should be inside async block")
def await[G[_],T,F[_]](f: G[T])(using CpsMonadCoversion[G,F], CpsMonadContext[F]): T
F[_]. — Our monad : Future[T], IO[T], … etc
G[_]. — Monad which we await
8. transparent inline
def async[F[_]](using am: CpsMonad[F])[T](inline f: am.Context ?=> T):F[T]
API (simpli
fi
ed)
@compileTimeOnly("await should be inside async block")
def await[G[_],T,F[_]](f: G[T])(using CpsMonadCoonversion[G,F], CpsMonadContext[F]): T
Using implementation of type class,
available in the current scope
9. transparent inline
def async[F[_]](using am: CpsMonad[F])[T](inline f: am.Context ?=> T):F[T]
API (simpli
fi
ed)
Context function
trait FutureMonad extends CpsMonad[Future] {
type Context = FutureContex
}
async[Future] {
// provide API, aviable only inside async
summon[FutureContext].executionContext.submit(..)
......
}
12. Transformations: control-
fl
ow (monadi
fi
cation, based on cps-transform)
CF[{a; b}]
F . flatMap(CF[a])(_ ⇒ CF[b])
CF[t] : t ∈ Constant ∨ t ∈ Identifier
F . pure(t)
// rules for control-
fl
ow constructions are straightforward
CF[val a = b; c]
F . flatMap(CF[a])(a′

⇒ CF[bx/x′

])
CF[if a then b else c]
F . flatMap(CF[a])(a′

⇒ if (a′

) then CF[b] else CF[c])
CF[throw ex]
F . error(ex)
13. Transformations: control-
fl
ow, optimisations
F . flatMap(F . pure(a))(x ⇒ F . pure(b(x))
F . pure(b(a))
Two sequential synchronous fragments are merged into one:
Transformation of each control-
fl
ow construction are specialised again sync/async components :
if a then b else c CF[a] ≠ F . pure(a) ∧ (CF[b] ≠ F . pure(b) ∨ CF[c] ≠ F . pure(c))
CF[a] = F . pure(a) ∧ (CF[b] ≠ F . pure(b) ∨ CF[c] ≠ F . pure(c))
CF[a] = F . pure(a) ∧ CF[b] = F . pure(b) ∧ CF[c] = F . pure(c)
n(bounds) ~ n(awaits):
Performance == performance of concurrent framework.
14. Transformations: higher-order functions
class Cache[K,V] {
def getOrUpdate(k:K, whenAbsent: =>V): V
}
Call by name, synonym of ()=>V
async[Process]{
val k = retrieveKey(request)
cache.getOrUpdate(k, await(fetchValue(k)))
}
Usual answer: continuation support in runtime environment.
type(CF[(x : T)]) = F[T], is not function
type(CF[(x : A ⇒ B)]) = A ⇒ type(CF[B])
Problem: JVM Runtime (as Js and Native now) have no continuations support
Allow programmer to de
fi
ne async ‘shifted’ variant of function via typecalss.
15. Transformations: higher-order functions
class Cache[K,V] {
def getOrUpdate(k:K, whenAbsent: =>V): V
}
async[Process]{
val k = retrieveKey(request)
cache.getOrUpdate(k, await(fetchValue(k)))
}
class CacheAsyncShift[K,V] extends
AsyncShift[Cache[K,V]]{
def getOrUpdate[F[_]](o:Cache[K,V],m:CpsMonad[F])
(k:K, whenAbsent: ()=> F[V]):F[V] =
....
}
summon[AsyncCache[Cache[K,V]]].getOrUpdate[F](cache,monad)(k, ()=>fetchValue(k))
// where monad = summon[CpsMonad[F]]
16. Transformations: higher-order functions
class Cache[K,V] {
def getOrUpdate(k:K, whenAbsent: =>V): V
def getOrUpdateAsync[F[_]](m:CpsMonad[F])(k:K, whenAbsent: ()=>F[V]): F[V]
}
async[Process]{
val k = retrieveKey(request)
cache.getOrUpdate(k, await(fetchValue(k)))
}
cache.getOrUpdateAsync[F](monad)(k, ()=>fetchValue(k))
// where monad = summon[CpsMonad[F]]
// author aware about dotty-cps-async
17. substitution classes for chain of higher-order methods
class Collection[A] {
def map(f: A=>B): Collection[B]
def withFilter(p: A=>Boolean): FilteredCollection[A]
}
for { url <- urls if await(score(url)) > limit) }
yield await(fetchData(url))
urls.withFilter(url => await(score(url))>limit).map(await(fetchData(url)))
Developer expect that combination of map and
fi
lter will work at the same way, as in synchronous case.
Collection FilteredCollection Result
Element 1
Element 2
……..
18. substitution classes for chain of higher-order methods
class Collection[A] {
def map(f: A=>B): Collection[B]
def withFilter(p: A=>Boolean): FilteredCollection[A]
}
class FilteredCollectionAsyncSubst[F[_],A](m:CpsMonad[F])
extends CallChainAsyncShiftSubst[F, FilteredCollection[A], FilteredCollectionAsyncSubst[F,A]]:
def _finishChain: FilteredCollection[A]
def withFilter(p: A=> Boolean): this.type
def withFilterAsync(p: A=>F[Boolean]): this.type
def map[B](f: A => B): this.type
def mapAsync[B](f: A=>F[B]): this.type
class AsyncShiftCollectin extends AsyncShift[Collection[A]]:
def withFilter[F[_]](c:Collection[A],m:CpsMonad[F])
(p: A=>F[Boolean]): FilteredCollectionAsyncSubst[F,A]
//. accumulate all ho-methods in chain, interpret via _
fi
nishChain
//categorical interpretation — left Kan extension for FilteredCollection
19. Transformations:
class Collection[A] {
def map(f: A=>B): Collection[B]
def withFilter(p: A=>Boolean): FilteredCollection[A]
}
class FilteredCollectionAsyncSubst[F[_],A](m:CpsMonad[F])
extends CallChainAsyncShiftSubst[F, FilteredCollection[A], FilteredCollectionAsyncSubst[F,A]]:
def _finishChain: FilteredCollection[A]
def withFilter(p: A=> Boolean): this.type
def withFilterAsync(p: A=>F[Boolean]): this.type
def map[B](f: A => B): this.type
def mapAsync[B](f: A=>F[B]): this.type
class AsyncShiftCollectin extends AsyncShift[Collection[A]]:
def withFilter[F[_]](c:Collection[A],m:CpsMonad[F])
(p: A=>F[Boolean]): FilteredCollectionAsyncSubst[F,A]
//. accumulate all ho-methods in chain, interpret via _
fi
nishChain
//categorical interpretation — left Kan extension for FilteredCollection
20. substitution classes for chain of higher-order methods
class Collection[A] {
def map(f: A=>B): Collection[B]
def withFilter(p: A=>Boolean): FilteredCollection[A]
}
class FilteredCollectionAsyncSubst[F[_],A](m:CpsMonad[F])
extends CallChainAsyncShiftSubst[F, FilteredCollection[A], FilteredCollecti
def _finishChain: FilteredCollection[A]
def withFilter(p: A=> Boolean): this.type
def withFilterAsync(p: A=>F[Boolean]): this.type
def map[B](f: A => B): this.type
def mapAsync[B](f: A=>F[B]): this.type
//. accumulate all ho-methods in chain, interpret via _
fi
nishChain
//categorical interpretation — left Kan extension for FilteredCollection
urls.withFilter(url => await(score(url))>limit).map(await(fetchData(url)))
summon[AsynsChift[Collection[A]].
withFilterAsync(url => score(url).map(x => x>limit)).mapAsync(fetchData(url))
21. Automatic colouring.
async[IO] {
val r1 = cacheService.getOrUpdate(id,
await(talkToServer(id)))
val r2 = talkToServer(r1.data)
if (r2.isOk) then
writeToFile(r1.data)
IO.println("done")
true
else
IO.println("abort")
false
}
async[IO] {
val r1 = cacheService.getOrUpdate(id,
await(talkToServer(id)))
val r2 = talkToServer(r1.data)
if (await(r2).isOk) then
await(writeToFile(r1.data))
await(IO.println(“done”))
true
else
await(IO.println(“abort”))
false
}
x : F[T]) → await(x) : T . implicit conversion:F[T] ⇒ T
discarded value F[T] → discarded value await(F[T])
22. Automatic colouring.
async[IO] {
val r1 = cacheService.getOrUpdate(id,
await(talkToServer(id)))
val r2 = talkToServer(r1.data)
if (r2.isOk) then
writeToFile(r1.data)
IO.println("done")
true
else
IO.println("abort")
false
}
async[IO] {
val r1 = cacheService.getOrUpdate(id,
await(talkToServer(id)))
val r2 = talkToServer(r1.data)
if (await(r2).isOk) then
await(writeToFile(r1.data))
await(IO.println(“done”))
true
else
await(IO.println(“abort”))
false
}
x : F[T]) → await(x) : T . implicit conversion:F[T] ⇒ T
discarded value F[T] → discarded value await(F[T])
Problem: this can be unsafe for some type of monads.
// disabled by default, enabled by import
23. Automatic colouring.
x : F[T]) → await(x) : T . implicit conversion:F[T] ⇒ T
discarded value F[T] → discarded value await(F[T])
This can be unsafe for some type of monads:
def run(): F[Unit] = async[F] {
val connection = openConnection()
try
while
val command = readCommand(connection)
val reply = handle(command)
if (!reply.isMuted)
connection.send(reply.toBytes)
!command.isShutdown
do ()
finally
connection.close()
}
def run(): F[Unit] = async[F] {
val connection = openConnection()
try
while
val command = readCommand(await(connection))
val reply = handle(await(command))
if (!await(reply).isMuted)
await(connection).send(await(reply).toBytes)
!await(command).isShutdown
do ()
finally
await(connection).close()
}
F[_]. Is cached, I.e. two usages refers to the same instance — Safe. (Example: Future)
F[_]. Is effect, I.e. two usage produce two effect — Unsafe. (Example: IO)
24. Automatic colouring.
x : F[T]) → await(x) : T . implicit conversion:F[T] ⇒ T
discarded value F[T] → discarded value await(F[T])
This can be unsafe for some type of monads:
def run(): F[Unit] = async[F] {
val connection = openConnection()
try
while
val command = readCommand(connection)
val reply = handle(command)
if (!reply.isMuted)
connection.send(reply.toBytes)
!command.isShutdown
do ()
finally
connection.close()
}
def run(): F[Unit] = async[F] {
val connection = openConnection()
try
while
val command = readCommand(await(connection))
val reply = handle(await(command))
if (!await(reply).isMuted)
await(connection).send(await(reply).toBytes)
!await(command).isShutdown
do ()
finally
await(connection).close()
}
F[_]. Is cached, I.e. two usages refers to the same instance — Safe. (Example: Future)
F[_]. Is effect, I.e. two usage produce two effect — Unsafe. (Example: IO)
25. Automatic colouring.
x : F[T]) → await(x) : T . implicit conversion:F[T] ⇒ T
discarded value F[T] → discarded value await(F[T])
F[_]. Is effect, I.e. two usage produce two effect — Unsafe. (Example: IO)
memoize : F[T] ⇒ F[F[T]]
def run(): F[Unit] = async[F] {
val connection = await(memoize(openConnection()))
try
while
val command = await(memoize(readCommand(await(connection))))
val reply = await(memoize(handle(await(command))))
if (!await(reply).isMuted)
await(connection).send(await(reply).toBytes)
!await(command).isShutdown
do ()
finally
await(connection).close()
}
26. Automatic colouring.
x : F[T]) → await(x) : T . implicit conversion:F[T] ⇒ T
discarded value F[T] → discarded value await(F[T])
F[_]. Is effect, I.e. two usage produce two effect — Unsafe. (Example: IO)
Unsafe, when we mix synchronous and asynchronous usage.
memoize : F[T] ⇒ F[F[T]]
Preliminary code analysis two prevent such mixing:
v : F[T]var, U(v) − all usages of v
u ∈ U(V)
sync(u) ⟺ u ⊏ await(v)
async(u) ⟺ ¬sync(u) ∧ ¬(u ⊏ (x = v))
discarded(u)
u2 ⊏ (v1 = v2) ⇒ U(v1) ⊂ U(v2)
¬∃u1, u2 ∈ U(v) : sync(u1) ∧ async(u2)
Safety condition:
27. Patterns of practical usage:
- Migrating from scala2 SIP22 async/await to Scala3 with dotty-cps-async. (Chat-server)
- Monad: Future
- Utility server for integration of freeswitch with external database.
- Monad: [X] =>> Resource[IO,X]
- Stack [ postgres, skunk, http4s ].
- Port of scala library for implementing csp-channels. [scala-gopher]
- (Non-trivial usage, inline syntax sugar api inside async block)
- Monad: generic + ReadChannel
Issues:
- (near 1/2) are compiler issues.
- other: ergonomica and handling specialised cases.
https://github.com/rssh/dotty-cps-async
28. Ruslan Shevchenko, Kyiv, Ukraine.
<ruslan@shevchenko.kiev.ua>
proofspace.id
Embedding Generic Monadic Transformer into Scala.
{Questions ? }
https://github.com/rssh/dotty-cps-async