The document discusses functional programming concepts like pure functions, immutable data, and avoiding side effects. It compares imperative programming constructs like loops and mutable state to functional alternatives like map, filter, reduce. It argues that a functional style enables better reasoning about programs by avoiding side effects and complex control flow. Specific examples show transforming an imperative loop into a functional map and handling asynchronous code through chained promises or futures. Overall it advocates for a functional programming approach.
Помните легендарные Java Puzzlers? Да-да, те самые, с Джошом Блохом и Нилом Гафтером? Ну, по которым ещё книжку написали? Так вот, в Groovy всё ещё веселее.
В смысле — задачки ещё более странные, и ответы ещё более поразительные. Этот доклад для вас, Groovy-разработчики, мы покажем вам настоящие, большие и красивые подводные камни! И для вас, Java-разработчики, потому что таких вещей на Java-подобном синтакисе вы точно никогда не видели! И для вас, PHP-разработчики… хотя, нет, не для вас :)
Всем точно будет весело — ваши ведущие Женя и Барух будут зажигать, шутить, спорить, бросаться футболками в публику, и самое главное — заставят вас офигевать от Groovy.
Programmation fonctionnelle en JavaScriptLoïc Knuchel
La programmation fonctionnelle permet de faire du code plus modulaire, avec moins de bugs et de manière plus productive !!!
Cette présentation montre comment la programmation fonctionnelle peut tenir se promesse et comment l'appliquer avec JavaScript.
imager package in R and example
References:
http://dahtah.github.io/imager/
http://dahtah.github.io/imager/imager.html
https://cran.r-project.org/web/packages/imager/imager.pdf
This document discusses Functor, Applicative Functor, Foldable and Traversable type classes in Haskell. It provides examples of using fmap, pure, (<*>), foldMap, traverse and sequenceA for different types like Maybe, lists and IO. It shows how Foldable is about folding while Traversable allows transforming elements of a structure with an Applicative. Traverse is used to define sequenceA and allows rejecting elements with negatives from a list.
The document shows examples of using lambda functions and functional programming techniques in various languages like JavaScript, Python, C#, and Java. It demonstrates how to define anonymous functions, map, filter and reduce collections, use closures, and more. Key examples include summing a list of integers with reduce, filtering even numbers from a list, mapping string transformations, and converting a list of strings to uppercase.
Advanced Data Visualization Examples with R-Part IIDr. Volkan OBAN
This document provides several examples of advanced data visualization techniques using R. It includes examples of 3D surface plots, contour plots, scatter plots and network graphs using various R packages like plot3D, scatterplot3D, ggplot2, qgraph and ggtree. Functions used include surf3D, contour3D, arrows3D, persp3D, image3D, scatter3D, qgraph, geom_point, geom_violin and ggtree. The examples demonstrate different visualization approaches for multivariate, spatial and network data.
Implementing virtual machines in go & c 2018 reduxEleanor McHugh
An updated version of my talk on virtual machine cores comparing techniques in C and Go for implementing dispatch loops, stacks & hash maps.
Lots of tested and debugged code is provided as well as references to some useful/interesting books.
Scala is a multi-paradigm programming language that supports functional, object-oriented and imperative programming paradigms. The document discusses Scala's support for types, expressions, objects, functions, and provides examples of using Scala for expressions, functions, control structures, patterns, spaces and actors.
The document provides examples of Kotlin classes and properties compared to Java classes. Some key points summarized:
1. Kotlin classes can define properties directly rather than private fields with getters/setters like in Java. Properties are accessed directly rather than through getter methods.
2. Data classes provide equals(), hashCode(), toString() by default and allow destructuring declarations. Regular classes do not have these features by default.
3. Default values can be defined for properties in Kotlin classes, unlike Java where default values require a builder pattern.
Some R Examples[R table and Graphics] -Advanced Data Visualization in R (Some...Dr. Volkan OBAN
Some R Examples[R table and Graphics]
Advanced Data Visualization in R (Some Examples)
References:
http://zevross.com/blog/2014/08/04/beautiful-plotting-in-r-a-ggplot2-cheatsheet-3/
http://www.cookbook-r.com/
http://moderndata.plot.ly/trisurf-plots-in-r-using-plotly/
I hope that it would ne useful for UseRs.
Umarım; R programı ile ilgilenen herkes için yararlı olur.
Volkan OBAN
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...PROIDEA
Contact
FUNCTIONAL PROGRAMING AND EVENT SOURCING - A PAIR MADE IN HEAVEN - EXTENDED, 2 HOURS LONG BRAINWASH
TL;DR: This is talk is a solid introduction to two (supposedly) different topics: FP & ES. I will cover both the theory and the practice. We will emerage ES+FP application starting from ES+OO one.
While reading blogs or attending conferences, you might have heard about Event Sourcing. But didn't you get this feeling, that while there is a lot of theory out there, it is really hard to see a hands-on example? And even if you find some, those are always orbiting around Object Oriented concepts?
Greg Young once said "When we talk about Event Sourcing, current state is a left-fold of previous behaviours. Nothing new to Functional Programmers". If Functional Programming is such a natural concept for event sourced systems, shouldn't they fit together on a single codebase?
In this talk we will quickly introduce Event Sourcing (but without going into details), we will introduce some functional concepts as well (like State monad). Armoured with that knowledge we will try to transform sample ES application (OO-style, tightly coupled with framework) to frameworkless, FP-style solution).
Talk is targeted for beginner and intermediate audience. Examples will be in Scala but nothing fancy - normal syntax.
This talk is an extended version of a presentation "Event Sourcing & Functional Programming - a pair made in heaven". It is enriched with content of presentations: "Monads - asking the right question" and "It's all been done before - The Hitchhiker's Guide to Time Travel".
The document discusses functional programming concepts in Scala including pure functions, referential transparency, algebraic data types, immutable linked lists, list folding, option types, higher order functions, and random number generation. It provides code examples for implementing immutable linked lists with pattern matching, list folding with foldLeft and foldRight, mapping, filtering and flatMapping lists, and defining monads and functors in Scala.
This document discusses various Ruby array and string methods like capitalize, each_char, map, sample, shuffle, zip, and more. Code snippets demonstrate how to use these methods on arrays and strings in Ruby. The document also discusses using Node.js and IRB to test Ruby code snippets and the potential to write tests for Ruby code using a BDD style.
This document provides an overview of Groovy's collection API. It discusses how Groovy treats many objects like collections, including strings, numbers, and regular expressions. It demonstrates various collection notation and operations, including lists, maps, ranges, and spread operators. It also summarizes common collection methods like each, find, collect, reducers, and useful utility methods like groupBy, countBy, and set operations.
This document provides examples of functional JavaScript code using point-free style and typeclasses. It includes code snippets demonstrating:
- Composing functions using point-free style to remove unnecessary variables
- Implementing common typeclass methods like map, chain, and ap for a Container type
- Deriving typeclass instances for custom types to gain functionality like Functor, Applicative, Foldable
- Using typeclasses to compose functions operating on different container types in a uniform way
The document provides code samples but does not explain concepts in detail. It focuses on demonstrating point-free code and typeclass patterns through examples rather than performing in-depth explanations or performance analysis. Questions are provided at the end to prompt
Functional Reactive Programming in JavascriptBrian Lonsdorf
Lightning is a giant discharge of electricity that can reach over five miles in length and raise air temperatures to 50,000 degrees Fahrenheit. On average, over 100 lightning bolts strike the Earth every second. Lightning is not confined to thunderstorms and has been seen in volcanic eruptions, forest fires, nuclear explosions, and heavy snowstorms.
This document covers key concepts in functional JavaScript including:
1) First class functions, loops, purity, type signatures, partial application, and composition.
2) It discusses the differences between imperative vs declarative programming and defines pure functions.
3) Various exercises are presented to reinforce these functional programming concepts.
This document discusses applicative functors in Haskell. It introduces the pure and ap functions that are used to define an applicative functor. It also discusses how applicative functors are closed under composition and how liftA and liftA2 can be defined in terms of fmap. It provides examples of using applicative functors with lists and discusses eventual results like combinators, comprehensions, and parallel computations.
The document discusses issues with using Underscore.js for functional programming concepts like currying, composition, and functors. Specifically, it notes that Underscore's API prevents currying functions and extending the map method, promoting chain over composition. The document suggests using Wu.js instead for a more functional approach.
Мы закончим обзор новых возможностей Node.js и сложив все это вместе в Node.js Starter Kit (шаблона проекта) от сообщества Metarhia для построения надежных и масштабируемых облачных и кластерных приложений и быстрой разработки API для высоконагруженных и интерактивных систем. Будет опубликован манифест Metaserverless. Мы разберем код, обсудим использование новейших возможностей платформы Node.js и фундаментальных знаний CS для построения грамотной структуры и архитектуры проекта.
1. The document discusses various techniques for limiting concurrency in Node.js applications to avoid resource starvation, including using a counter variable, asynchronous queue, counting semaphore, or external load balancer with monitoring.
2. Examples are given of using an asynchronous queue and counting semaphore to limit concurrency, with references provided to open source implementations.
3. The V8 serialization API is described as a way to serialize JavaScript objects to pass between contexts, with examples of serializing and deserializing an array.
The document discusses various built-in functions in Python including numeric, string, and container data types. It provides examples of using list comprehensions, dictionary comprehensions, lambda functions, enumerate, zip, filter, any, all, map and reduce to manipulate data in Python. It also includes references to online resources for further reading.
How are Race Conditions in single threaded JavaScript possible?Timur Shemsedinov
Race conditions in single-threaded JavaScript are possible due to asynchronous code execution using callbacks, promises, and async/await. Common concurrency problems include race conditions, deadlocks, and resource starvation. Potential solutions include synchronization primitives like mutexes and semaphores, resource locking, and flow commutation to control the order of asynchronous operations.
The document describes a Haskell program that translates characters in one string to characters in another string. It defines a translate function that maps characters from the first string (set1) to the corresponding characters in the second string (set2). A translateString function applies the translate function to a given string, and the main function gets the set1 and set2 strings from arguments, reads stdin, applies translateString, and writes the result to stdout, catching any errors.
This document contains code snippets from the evolution of programming languages presented in a table with multiple rows. Each row contains code from a different language such as machine code, assembly, Fortran, Basic, Lisp, Algol 60, C, C++, Ada, dBase, FoxBase, Clipper, Haskell, Python, Java, Delphi, SQL, PHP, C#, and others. The code snippets demonstrate features from each language through short programs.
Новое в JavaScript: ES.Next, ECMAScript 2020, ES11, ES10, ES9, ES8, ES7, ES6,...Timur Shemsedinov
This document summarizes new features in JavaScript including ES2020 and beyond. It discusses updates to built-in objects like Array, Object, String, operators like optional chaining and nullish coalescing, asynchronous functions with async/await, and new Promise methods like Promise.allSettled. It also covers trailing commas, symbols, and other language features.
I'll found many papers and books talking about category theory, but many peoples still don't know how it can help. On this talk I'll help you better understand how math can help us develop a software more composable.
Coder on Beer - Concrete
2018 - São Paulo
The document discusses software design patterns and principles including:
1. GRASP (General Responsibility Assignment Software Patterns) which deals with assigning responsibilities and coupling/cohesion.
2. SOLID principles for object-oriented design including single responsibility, open/closed, Liskov substitution etc.
3. Design patterns from the Gang of Four (GoF) book including creational, structural and behavioral patterns.
It provides examples of how these concepts relate to JavaScript and Node.js application architecture by discussing concerns like layers, abstraction and separation of concerns.
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.
Implementing Software Machines in C and GoEleanor McHugh
The next iteration of the talk I gave at Progscon, this introduces examples of Map implementation (useful for caches etc.) and outlines for addition of processor core code in a later talk.
This document discusses asynchronous programming in Node.js. It covers callbacks, promises, async/await and other approaches. Some key points made include:
- Callbacks can lead to "callback hell" with deeply nested code. Separating functions and following error-first conventions can help.
- Promises separate control flow for success and failure cases compared to callbacks. Complex parallel/sequential code can still be difficult.
- Async/await makes asynchronous code look synchronous but still uses promises under the hood. It can also lead to nested code issues.
- Other approaches discussed include EventEmitters, generators/yield, observables and asynchronous composition utilities. The document compares strengths and limitations of different approaches.
This document provides examples of Python code snippets covering various topics like Python basics (print, variables, data types), conditional statements (if-else), loops (for, while), functions, object oriented programming (classes, inheritance), file handling, modules, database connectivity (MySQL, Redis), XML/HTML parsing and web scraping. It also shows code for installing and importing various third party Python libraries and modules.
R + Hadoop = Big Data Analytics. How Revolution Analytics' RHadoop Project Al...Revolution Analytics
R can be used for big data analytics by integrating it with Hadoop via packages like rmr that allow R code to be run on Hadoop clusters using the mapreduce programming model. This exposes the mapreduce API within R and hides the complexity of Hadoop. Other R packages provide interfaces to higher level frameworks built on Hadoop like Hive and Pig. The document provides examples of using R and rmr to perform mapreduce operations like kmeans clustering on large datasets stored in Hadoop. It also shows how a kmeans algorithm can be implemented in Pig Latin and integrated with R through a Java UDF.
This document discusses Go programming concepts including concurrency, reflection, interfaces, and generics. It provides examples of using channels for concurrency, reflecting over types, implementing interfaces, and defining generic functions. The examples demonstrate capabilities like mapping and reducing over collections, duplicating values, and applying transformations.
Michael Fogus discusses creating a minimal Lisp variant using only 7 core functions and forms. He demonstrates how to build up common Lisp features like lists, conditionals, functions, and recursion using only the primitive functions car, cdr, cons, cond, label, lambda, and dynamic scoping. Through a series of examples, he shows how more advanced features can emerge from these basics alone, culminating in a meta-circular evaluator. He argues the core set could be reduced even further to just 3 primitive forms.
This document summarizes the key changes and new features introduced in Python 3, including:
- Strings are now unicode by default and implicit conversions between str and bytes are prohibited.
- Integers are unified under int and long is removed.
- New features like formatted string literals, function annotations, nonlocal and keyword-only arguments, extended iterable unpacking, comprehensions, exception chaining, and yield from.
- New collection abstract base classes and data structures like OrderedDict and Counter.
- Metaclasses can now control class creation and new metaclass like OrderedClass is introduced.
- Under the hood improvements including a new GIL and stable ABI version tagged shared object files.
Sustainability requires ingenuity and stewardship. Did you know Pigging Solutions pigging systems help you achieve your sustainable manufacturing goals AND provide rapid return on investment.
How? Our systems recover over 99% of product in transfer piping. Recovering trapped product from transfer lines that would otherwise become flush-waste, means you can increase batch yields and eliminate flush waste. From raw materials to finished product, if you can pump it, we can pig it.
Details of description part II: Describing images in practice - Tech Forum 2024BookNet Canada
This presentation explores the practical application of image description techniques. Familiar guidelines will be demonstrated in practice, and descriptions will be developed “live”! If you have learned a lot about the theory of image description techniques but want to feel more confident putting them into practice, this is the presentation for you. There will be useful, actionable information for everyone, whether you are working with authors, colleagues, alone, or leveraging AI as a collaborator.
Link to presentation recording and transcript: https://bnctechforum.ca/sessions/details-of-description-part-ii-describing-images-in-practice/
Presented by BookNet Canada on June 25, 2024, with support from the Department of Canadian Heritage.
How RPA Help in the Transportation and Logistics Industry.pptxSynapseIndia
Revolutionize your transportation processes with our cutting-edge RPA software. Automate repetitive tasks, reduce costs, and enhance efficiency in the logistics sector with our advanced solutions.
7 Most Powerful Solar Storms in the History of Earth.pdfEnterprise Wired
Solar Storms (Geo Magnetic Storms) are the motion of accelerated charged particles in the solar environment with high velocities due to the coronal mass ejection (CME).
RPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptxSynapseIndia
Your comprehensive guide to RPA in healthcare for 2024. Explore the benefits, use cases, and emerging trends of robotic process automation. Understand the challenges and prepare for the future of healthcare automation
Comparison Table of DiskWarrior Alternatives.pdfAndrey Yasko
To help you choose the best DiskWarrior alternative, we've compiled a comparison table summarizing the features, pros, cons, and pricing of six alternatives.
YOUR RELIABLE WEB DESIGN & DEVELOPMENT TEAM — FOR LASTING SUCCESS
WPRiders is a web development company specialized in WordPress and WooCommerce websites and plugins for customers around the world. The company is headquartered in Bucharest, Romania, but our team members are located all over the world. Our customers are primarily from the US and Western Europe, but we have clients from Australia, Canada and other areas as well.
Some facts about WPRiders and why we are one of the best firms around:
More than 700 five-star reviews! You can check them here.
1500 WordPress projects delivered.
We respond 80% faster than other firms! Data provided by Freshdesk.
We’ve been in business since 2015.
We are located in 7 countries and have 22 team members.
With so many projects delivered, our team knows what works and what doesn’t when it comes to WordPress and WooCommerce.
Our team members are:
- highly experienced developers (employees & contractors with 5 -10+ years of experience),
- great designers with an eye for UX/UI with 10+ years of experience
- project managers with development background who speak both tech and non-tech
- QA specialists
- Conversion Rate Optimisation - CRO experts
They are all working together to provide you with the best possible service. We are passionate about WordPress, and we love creating custom solutions that help our clients achieve their goals.
At WPRiders, we are committed to building long-term relationships with our clients. We believe in accountability, in doing the right thing, as well as in transparency and open communication. You can read more about WPRiders on the About us page.
INDIAN AIR FORCE FIGHTER PLANES LIST.pdfjackson110191
These fighter aircraft have uses outside of traditional combat situations. They are essential in defending India's territorial integrity, averting dangers, and delivering aid to those in need during natural calamities. Additionally, the IAF improves its interoperability and fortifies international military alliances by working together and conducting joint exercises with other air forces.
Best Practices for Effectively Running dbt in Airflow.pdfTatiana Al-Chueyr
As a popular open-source library for analytics engineering, dbt is often used in combination with Airflow. Orchestrating and executing dbt models as DAGs ensures an additional layer of control over tasks, observability, and provides a reliable, scalable environment to run dbt models.
This webinar will cover a step-by-step guide to Cosmos, an open source package from Astronomer that helps you easily run your dbt Core projects as Airflow DAGs and Task Groups, all with just a few lines of code. We’ll walk through:
- Standard ways of running dbt (and when to utilize other methods)
- How Cosmos can be used to run and visualize your dbt projects in Airflow
- Common challenges and how to address them, including performance, dependency conflicts, and more
- How running dbt projects in Airflow helps with cost optimization
Webinar given on 9 July 2024
Mitigating the Impact of State Management in Cloud Stream Processing SystemsScyllaDB
Stream processing is a crucial component of modern data infrastructure, but constructing an efficient and scalable stream processing system can be challenging. Decoupling compute and storage architecture has emerged as an effective solution to these challenges, but it can introduce high latency issues, especially when dealing with complex continuous queries that necessitate managing extra-large internal states.
In this talk, we focus on addressing the high latency issues associated with S3 storage in stream processing systems that employ a decoupled compute and storage architecture. We delve into the root causes of latency in this context and explore various techniques to minimize the impact of S3 latency on stream processing performance. Our proposed approach is to implement a tiered storage mechanism that leverages a blend of high-performance and low-cost storage tiers to reduce data movement between the compute and storage layers while maintaining efficient processing.
Throughout the talk, we will present experimental results that demonstrate the effectiveness of our approach in mitigating the impact of S3 latency on stream processing. By the end of the talk, attendees will have gained insights into how to optimize their stream processing systems for reduced latency and improved cost-efficiency.
Support en anglais diffusé lors de l'événement 100% IA organisé dans les locaux parisiens d'Iguane Solutions, le mardi 2 juillet 2024 :
- Présentation de notre plateforme IA plug and play : ses fonctionnalités avancées, telles que son interface utilisateur intuitive, son copilot puissant et des outils de monitoring performants.
- REX client : Cyril Janssens, CTO d’ easybourse, partage son expérience d’utilisation de notre plateforme IA plug & play.
The DealBook is our annual overview of the Ukrainian tech investment industry. This edition comprehensively covers the full year 2023 and the first deals of 2024.
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...Bert Blevins
Today’s digitally connected world presents a wide range of security challenges for enterprises. Insider security threats are particularly noteworthy because they have the potential to cause significant harm. Unlike external threats, insider risks originate from within the company, making them more subtle and challenging to identify. This blog aims to provide a comprehensive understanding of insider security threats, including their types, examples, effects, and mitigation techniques.
Coordinate Systems in FME 101 - Webinar SlidesSafe Software
If you’ve ever had to analyze a map or GPS data, chances are you’ve encountered and even worked with coordinate systems. As historical data continually updates through GPS, understanding coordinate systems is increasingly crucial. However, not everyone knows why they exist or how to effectively use them for data-driven insights.
During this webinar, you’ll learn exactly what coordinate systems are and how you can use FME to maintain and transform your data’s coordinate systems in an easy-to-digest way, accurately representing the geographical space that it exists within. During this webinar, you will have the chance to:
- Enhance Your Understanding: Gain a clear overview of what coordinate systems are and their value
- Learn Practical Applications: Why we need datams and projections, plus units between coordinate systems
- Maximize with FME: Understand how FME handles coordinate systems, including a brief summary of the 3 main reprojectors
- Custom Coordinate Systems: Learn how to work with FME and coordinate systems beyond what is natively supported
- Look Ahead: Gain insights into where FME is headed with coordinate systems in the future
Don’t miss the opportunity to improve the value you receive from your coordinate system data, ultimately allowing you to streamline your data analysis and maximize your time. See you there!
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...Erasmo Purificato
Slide of the tutorial entitled "Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Emerging Trends" held at UMAP'24: 32nd ACM Conference on User Modeling, Adaptation and Personalization (July 1, 2024 | Cagliari, Italy)
18. const dotChainy = str => {
const lower = str.toLowerCase()
const words = lower.split(' ')
words.reverse()
for(let i in words) {
words[i] = words[i].trim()
}
let keepers = []
for(let i in words) {
if(words[i].length > 3) {
keepers.push(words[i])
}
}
return keepers.join('')
}
19. const dotChainy = str => {
const lower = str.toLowerCase()
const words = lower.split(' ')
words.reverse()
for(let i in words) {
words[i] = words[i].trim()
}
let keepers = []
for(let i in words) {
if(words[i].length > 3) {
keepers.push(words[i])
}
}
return keepers.join('')
}
20. class AppMailer {
constructor() {
this.emailer = new Emailer()
}
removeInvalidAddresses() {
for(let i in this.addresses) {
if(!this.addresses[i].match(/@/)) {
this.addresses.splice(i, 1)
}
}
}
sendEmail({from, to}) {
this.addresses = to
this.emailer.setSender(from)
this.removeInvalidAddresses()
this.emailer.setRecipients(this.addresses)
this.emailer.send()
}
22. “the major contributor to this complexity in many systems is
the handling of state and the burden that this adds when
trying to analyse and reason about the system.”
Out of the Tar Pit 2006
-Ben Moseley & Peter Marks
34. for(let thing in things) {
if(thing.amount > 100) keepers.push(thing.name)
}
for (i = 0; i < cars.length; i++) {
text += cars[i] + "<br>";
}
while (i < 10) {
text += "The number is " + i;
i++;
}
86. Left('no ducks :(').fold(e => `we had an error: ${e}`,
s => s.toUpperCase())
// we had an error: no ducks :(
Right('ducks').fold(e => `we had an error: ${e}`,
s => s.toUpperCase())
//"DUCKS"
87. Left('no ducks :(').fold(e => `we had an error: ${e}`,
s => s.toUpperCase())
// we had an error: no ducks :(
Right('ducks').fold(e => `we had an error: ${e}`,
s => s.toUpperCase())
//"DUCKS"
88. Left('no ducks :(').fold(e => `we had an error: ${e}`,
s => s.toUpperCase())
// we had an error: no ducks :(
Right('ducks').fold(e => `we had an error: ${e}`,
s => s.toUpperCase())
//"DUCKS"
123. const Reducer = g =>
({
fold: g,
contramap: f =>
Reducer((acc, x) => g(acc, f(x))),
map: f =>
Reducer((acc, x) => f(g(acc, x)))
})
124. const r = Reducer((acc, x) => acc.concat(x))
.contramap(x => `The number is ${x}`)
.map(x => x + '! ')
[1,2,3].reduce(r.fold, '')
// The number is 1! The number is 2! The number is 3!
const Reducer = g =>
({
fold: g,
contramap: f =>
Reducer((acc, x) => g(acc, f(x))),
map: f =>
Reducer((acc, x) => f(g(acc, x)))
})
125. const Reducer = g =>
({
fold: g,
contramap: f =>
Reducer((acc, x) => g(acc, f(x))),
map: f =>
Reducer((acc, x) => f(g(acc, x)))
})
126. const Reducer = g =>
({
fold: g,
contramap: f =>
Reducer((acc, x) => g(acc, f(x))),
map: f =>
Reducer((acc, x) => f(g(acc, x))),
concat: o =>
Reducer((acc, x) => o.fold(g(acc, x), x))
})