Language is everything; it governs our lives: from our thought processes, our communication abilities and our understanding of the world, all the way up to law, politics, logic and programming. All of these domains of human experience are governed by different languages that talk to each other, and so should be your code. Haskell provides all the means necessary—and many more—to easily and safely use embedded small languages that are tailored to specific needs and business domains.
In this series of lectures and workshops, we will explore the whats, whys and hows of embedded domain-specific languages in Haskell, and how language oriented programing can bring type-safety, composability and simplicity to the development of complex applications.
Learning from other's mistakes: Data-driven code analysisAndreas Dewes
Static code analysis is an useful tool that can help to detect bugs early in the software development life cycle. I will explain the basics of static analysis and show the challenges we face when analyzing Python code. I will introduce a data-driven approach to code analysis that makes use of public code and example-based learning and show how it can be applied to analyzing Python code.
Code is not text! How graph technologies can help us to understand our code b...Andreas Dewes
Today, we almost exclusively think of code in software projects as a collection of text files. The tools that we use (version control systems, IDEs, code analyzers) also use text as the primary storage format for code. In fact, the belief that “code is text” is so deeply ingrained in our heads that we never question its validity or even become aware of the fact that there are other ways to look at code.
In my talk I will explain why treating code as text is a very bad idea which actively holds back our understanding and creates a range of problems in large software projects. I will then show how we can overcome (some of) these problems by treating and storing code as data, and more specifically as a graph. I will show specific examples of how we can use this approach to improve our understanding of large code bases, increase code quality and automate certain aspects of software development.
Finally, I will outline my personal vision of the future of programming, which is a future where we no longer primarily interact with code bases using simple text editors. I will also give some ideas on how we might get to that future.
This session will introduce you to the new Form component in Symfony2. With the new domain-driven paradigma and its flexible design, the component opens a door to a wide range of possibilities. The brand new architecture makes creating complex forms easier and faster than ever before. This talk will teach you today what you need to know to build powerful forms tomorrow.
In this talk, Adrian Kashivskyy, Netguru iOS Developer, digs into rarely discussed Swift features, such as literal convertibles, interpolation convertibles, pattern matching, reflection and advanced Objective-C bridging.
Everything you always wanted to know about forms* *but were afraid to askAndrea Giuliano
La componente dei Form di Symfony2 rende possibile la costruzione di diverse tipologie di form in modo del tutto semplice. La sua architettura flessibile e altamente scalabile permette di poter gestire strutture adatte ad ogni tipo di esigenza. Tuttavia, conoscere come utilizzare appieno tutta la sua potenza non è banale. In questo talk verrà trattato in profondità la componente Form di Symfony2, mostrando i suoi meccanismi di base e come utilizzarli per estenderli ed introdurre la propria logica di business, così da costruire form cuciti a misura delle tue necessità.
Learning from other's mistakes: Data-driven code analysisAndreas Dewes
Static code analysis is an useful tool that can help to detect bugs early in the software development life cycle. I will explain the basics of static analysis and show the challenges we face when analyzing Python code. I will introduce a data-driven approach to code analysis that makes use of public code and example-based learning and show how it can be applied to analyzing Python code.
Code is not text! How graph technologies can help us to understand our code b...Andreas Dewes
Today, we almost exclusively think of code in software projects as a collection of text files. The tools that we use (version control systems, IDEs, code analyzers) also use text as the primary storage format for code. In fact, the belief that “code is text” is so deeply ingrained in our heads that we never question its validity or even become aware of the fact that there are other ways to look at code.
In my talk I will explain why treating code as text is a very bad idea which actively holds back our understanding and creates a range of problems in large software projects. I will then show how we can overcome (some of) these problems by treating and storing code as data, and more specifically as a graph. I will show specific examples of how we can use this approach to improve our understanding of large code bases, increase code quality and automate certain aspects of software development.
Finally, I will outline my personal vision of the future of programming, which is a future where we no longer primarily interact with code bases using simple text editors. I will also give some ideas on how we might get to that future.
This session will introduce you to the new Form component in Symfony2. With the new domain-driven paradigma and its flexible design, the component opens a door to a wide range of possibilities. The brand new architecture makes creating complex forms easier and faster than ever before. This talk will teach you today what you need to know to build powerful forms tomorrow.
In this talk, Adrian Kashivskyy, Netguru iOS Developer, digs into rarely discussed Swift features, such as literal convertibles, interpolation convertibles, pattern matching, reflection and advanced Objective-C bridging.
Everything you always wanted to know about forms* *but were afraid to askAndrea Giuliano
La componente dei Form di Symfony2 rende possibile la costruzione di diverse tipologie di form in modo del tutto semplice. La sua architettura flessibile e altamente scalabile permette di poter gestire strutture adatte ad ogni tipo di esigenza. Tuttavia, conoscere come utilizzare appieno tutta la sua potenza non è banale. In questo talk verrà trattato in profondità la componente Form di Symfony2, mostrando i suoi meccanismi di base e come utilizzarli per estenderli ed introdurre la propria logica di business, così da costruire form cuciti a misura delle tue necessità.
Max Koretskyi "Why are Angular and React so fast?"Fwdays
Very few developers have the need to write super optimized code. In application development, we tend to favor readability over optimization. But that’s not the case with frameworks. Developers who use frameworks expect them to run as fast as possible. In fact, speed is often a defining characteristic when choosing a framework. There are techniques that make code run faster. You’ve probably heard about linked lists, monomorphism, and bitmasks, right? Maybe you've even used some. Well, you can find all these and a bunch of other interesting approaches in the sources of most popular JS frameworks.
Over the past year, I’ve seen a lot while reverse-engineering Angular and React. In this talk, I want to share my findings with you. Some of you may end up applying them at work. And others, who knows, may even end up writing the next big framework.
Esoft Metro Campus - Diploma in Web Engineering - (Module II) Multimedia Technologies
(Template - Virtusa Corporate)
Contents:
What is a Database?
The Relational Data Model
Relationships
Normalization
Functional Dependency
Normal Forms
DBMS
What is MySQL?
PHP Connect to MySQL
Create a MySQL Database
Connect to Database
Close Database
Create a MySQL Table
Insert Data Into MySQL
Get Last ID
Insert Multiple Records
Prepared Statements
Select Data From MySQL
Update Data in MySQL
Delete Data From MySQL
Things you should know about Javascript ES5. A programming language that enables you to create dynamically updating content, control multimedia, animate images, and pretty much everything else
SOLID - a set of concepts for designing maintainable and understandable software - yet some of these ideas can be hard to understand themselves. Scholarly definitions and generic examples of these are often still confusing and not applicable to real world applications. By taking a look at an actual application, we'll explore these principles in action, and demonstrate the benefits of following them.
Short (45 min) version of my 'Pragmatic Real-World Scala' talk. Discussing patterns and idioms discovered during 1.5 years of building a production system for finance; portfolio management and simulation.
Max Koretskyi "Why are Angular and React so fast?"Fwdays
Very few developers have the need to write super optimized code. In application development, we tend to favor readability over optimization. But that’s not the case with frameworks. Developers who use frameworks expect them to run as fast as possible. In fact, speed is often a defining characteristic when choosing a framework. There are techniques that make code run faster. You’ve probably heard about linked lists, monomorphism, and bitmasks, right? Maybe you've even used some. Well, you can find all these and a bunch of other interesting approaches in the sources of most popular JS frameworks.
Over the past year, I’ve seen a lot while reverse-engineering Angular and React. In this talk, I want to share my findings with you. Some of you may end up applying them at work. And others, who knows, may even end up writing the next big framework.
Esoft Metro Campus - Diploma in Web Engineering - (Module II) Multimedia Technologies
(Template - Virtusa Corporate)
Contents:
What is a Database?
The Relational Data Model
Relationships
Normalization
Functional Dependency
Normal Forms
DBMS
What is MySQL?
PHP Connect to MySQL
Create a MySQL Database
Connect to Database
Close Database
Create a MySQL Table
Insert Data Into MySQL
Get Last ID
Insert Multiple Records
Prepared Statements
Select Data From MySQL
Update Data in MySQL
Delete Data From MySQL
Things you should know about Javascript ES5. A programming language that enables you to create dynamically updating content, control multimedia, animate images, and pretty much everything else
SOLID - a set of concepts for designing maintainable and understandable software - yet some of these ideas can be hard to understand themselves. Scholarly definitions and generic examples of these are often still confusing and not applicable to real world applications. By taking a look at an actual application, we'll explore these principles in action, and demonstrate the benefits of following them.
Short (45 min) version of my 'Pragmatic Real-World Scala' talk. Discussing patterns and idioms discovered during 1.5 years of building a production system for finance; portfolio management and simulation.
JavaScript Objects and OOP Programming with JavaScriptLaurence Svekis ✔
Get this Course
https://www.udemy.com/javascript-objects-oop/?couponCode=SLIDESHARE
Use objects to create amazing things with JavaScript power up your applications OOP JavaScript coding
Você provavelmente já ouviu falar de Elm e suas promessas incríveis, mas você não quer reescrever tudo do zero, nem deixar a comunidade React. E se você pudesse ter todos os benefícios de Elm, enquanto ainda usa seus componentes React, misturando JavaScript e uma linguagem mais simples e poderosa, com um excelente sistema de tipos? Venha conhecer então PureScript e a biblioteca Pux!
These are slides from our Big Data Warehouse Meetup in April. We talked about NoSQL databases: What they are, how they’re used and where they fit in existing enterprise data ecosystems.
Mike O’Brian from 10gen, introduced the syntax and usage patterns for a new aggregation system in MongoDB and give some demonstrations of aggregation using the new system. The new MongoDB aggregation framework makes it simple to do tasks such as counting, averaging, and finding minima or maxima while grouping by keys in a collection, complementing MongoDB’s built-in map/reduce capabilities.
For more information, visit our website at http://casertaconcepts.com/ or email us at info@casertaconcepts.com.
Esoft Metro Campus - Diploma in Web Engineering - (Module VII) Advanced PHP Concepts
(Template - Virtusa Corporate)
Contents:
Arrays
Indexed Arrays
Associative Arrays
Multidimensional arrays
Array Functions
PHP Objects and Classes
Creating an Object
Properties of Objects
Object Methods
Constructors
Inheritance
Method overriding
PHP Strings
printf() Function
String Functions
PHP Date/Time Functions
time() Function
getdate() Function
date() Function
mktime() function
checkdate() function
PHP Form Handling
Collecting form data with PHP
GET vs POST
Data validation against malicious code
Required fields validation
Validating an E-mail address
PHP mail() Function
Using header() function to redirect user
File Upload
Processing the uploaded file
Check if File Already Exists
Limit File Size
Limit File Type
Check if image file is an actual image
Uploading File
Cookies
Sessions
Similar to Type safe embedded domain-specific languages (20)
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteGoogle
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
👉👉 Click Here To Get More Info 👇👇
https://sumonreview.com/ai-pilot-review/
AI Pilot Review: Key Features
✅Deploy AI expert bots in Any Niche With Just A Click
✅With one keyword, generate complete funnels, websites, landing pages, and more.
✅More than 85 AI features are included in the AI pilot.
✅No setup or configuration; use your voice (like Siri) to do whatever you want.
✅You Can Use AI Pilot To Create your version of AI Pilot And Charge People For It…
✅ZERO Manual Work With AI Pilot. Never write, Design, Or Code Again.
✅ZERO Limits On Features Or Usages
✅Use Our AI-powered Traffic To Get Hundreds Of Customers
✅No Complicated Setup: Get Up And Running In 2 Minutes
✅99.99% Up-Time Guaranteed
✅30 Days Money-Back Guarantee
✅ZERO Upfront Cost
See My Other Reviews Article:
(1) TubeTrivia AI Review: https://sumonreview.com/tubetrivia-ai-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
Quarkus Hidden and Forbidden ExtensionsMax Andersen
Quarkus has a vast extension ecosystem and is known for its subsonic and subatomic feature set. Some of these features are not as well known, and some extensions are less talked about, but that does not make them less interesting - quite the opposite.
Come join this talk to see some tips and tricks for using Quarkus and some of the lesser known features, extensions and development techniques.
Graspan: A Big Data System for Big Code AnalysisAftab Hussain
We built a disk-based parallel graph system, Graspan, that uses a novel edge-pair centric computation model to compute dynamic transitive closures on very large program graphs.
We implement context-sensitive pointer/alias and dataflow analyses on Graspan. An evaluation of these analyses on large codebases such as Linux shows that their Graspan implementations scale to millions of lines of code and are much simpler than their original implementations.
These analyses were used to augment the existing checkers; these augmented checkers found 132 new NULL pointer bugs and 1308 unnecessary NULL tests in Linux 4.4.0-rc5, PostgreSQL 8.3.9, and Apache httpd 2.2.18.
- Accepted in ASPLOS ‘17, Xi’an, China.
- Featured in the tutorial, Systemized Program Analyses: A Big Data Perspective on Static Analysis Scalability, ASPLOS ‘17.
- Invited for presentation at SoCal PLS ‘16.
- Invited for poster presentation at PLDI SRC ‘16.
Globus Connect Server Deep Dive - GlobusWorld 2024Globus
We explore the Globus Connect Server (GCS) architecture and experiment with advanced configuration options and use cases. This content is targeted at system administrators who are familiar with GCS and currently operate—or are planning to operate—broader deployments at their institution.
Check out the webinar slides to learn more about how XfilesPro transforms Salesforce document management by leveraging its world-class applications. For more details, please connect with sales@xfilespro.com
If you want to watch the on-demand webinar, please click here: https://www.xfilespro.com/webinars/salesforce-document-management-2-0-smarter-faster-better/
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Globus
The Earth System Grid Federation (ESGF) is a global network of data servers that archives and distributes the planet’s largest collection of Earth system model output for thousands of climate and environmental scientists worldwide. Many of these petabyte-scale data archives are located in proximity to large high-performance computing (HPC) or cloud computing resources, but the primary workflow for data users consists of transferring data, and applying computations on a different system. As a part of the ESGF 2.0 US project (funded by the United States Department of Energy Office of Science), we developed pre-defined data workflows, which can be run on-demand, capable of applying many data reduction and data analysis to the large ESGF data archives, transferring only the resultant analysis (ex. visualizations, smaller data files). In this talk, we will showcase a few of these workflows, highlighting how Globus Flows can be used for petabyte-scale climate analysis.
Software Engineering, Software Consulting, Tech Lead.
Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Security,
Spring Transaction, Spring MVC,
Log4j, REST/SOAP WEB-SERVICES.
First Steps with Globus Compute Multi-User EndpointsGlobus
In this presentation we will share our experiences around getting started with the Globus Compute multi-user endpoint. Working with the Pharmacology group at the University of Auckland, we have previously written an application using Globus Compute that can offload computationally expensive steps in the researcher's workflows, which they wish to manage from their familiar Windows environments, onto the NeSI (New Zealand eScience Infrastructure) cluster. Some of the challenges we have encountered were that each researcher had to set up and manage their own single-user globus compute endpoint and that the workloads had varying resource requirements (CPUs, memory and wall time) between different runs. We hope that the multi-user endpoint will help to address these challenges and share an update on our progress here.
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Globus
The U.S. Geological Survey (USGS) has made substantial investments in meeting evolving scientific, technical, and policy driven demands on storing, managing, and delivering data. As these demands continue to grow in complexity and scale, the USGS must continue to explore innovative solutions to improve its management, curation, sharing, delivering, and preservation approaches for large-scale research data. Supporting these needs, the USGS has partnered with the University of Chicago-Globus to research and develop advanced repository components and workflows leveraging its current investment in Globus. The primary outcome of this partnership includes the development of a prototype enterprise repository, driven by USGS Data Release requirements, through exploration and implementation of the entire suite of the Globus platform offerings, including Globus Flow, Globus Auth, Globus Transfer, and Globus Search. This presentation will provide insights into this research partnership, introduce the unique requirements and challenges being addressed and provide relevant project progress.
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamtakuyayamamoto1800
In this slide, we show the simulation example and the way to compile this solver.
In this solver, the Helmholtz equation can be solved by helmholtzFoam. Also, the Helmholtz equation with uniformly dispersed bubbles can be simulated by helmholtzBubbleFoam.
Listen to the keynote address and hear about the latest developments from Rachana Ananthakrishnan and Ian Foster who review the updates to the Globus Platform and Service, and the relevance of Globus to the scientific community as an automation platform to accelerate scientific discovery.
Code reviews are vital for ensuring good code quality. They serve as one of our last lines of defense against bugs and subpar code reaching production.
Yet, they often turn into annoying tasks riddled with frustration, hostility, unclear feedback and lack of standards. How can we improve this crucial process?
In this session we will cover:
- The Art of Effective Code Reviews
- Streamlining the Review Process
- Elevating Reviews with Automated Tools
By the end of this presentation, you'll have the knowledge on how to organize and improve your code review proces
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
Atelier - Innover avec l’IA Générative et les graphes de connaissancesNeo4j
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Allez au-delà du battage médiatique autour de l’IA et découvrez des techniques pratiques pour utiliser l’IA de manière responsable à travers les données de votre organisation. Explorez comment utiliser les graphes de connaissances pour augmenter la précision, la transparence et la capacité d’explication dans les systèmes d’IA générative. Vous partirez avec une expérience pratique combinant les relations entre les données et les LLM pour apporter du contexte spécifique à votre domaine et améliorer votre raisonnement.
Amenez votre ordinateur portable et nous vous guiderons sur la mise en place de votre propre pile d’IA générative, en vous fournissant des exemples pratiques et codés pour démarrer en quelques minutes.
Top 7 Unique WhatsApp API Benefits | Saudi ArabiaYara Milbes
Discover the transformative power of the WhatsApp API in our latest SlideShare presentation, "Top 7 Unique WhatsApp API Benefits." In today's fast-paced digital era, effective communication is crucial for both personal and professional success. Whether you're a small business looking to enhance customer interactions or an individual seeking seamless communication with loved ones, the WhatsApp API offers robust capabilities that can significantly elevate your experience.
In this presentation, we delve into the top 7 distinctive benefits of the WhatsApp API, provided by the leading WhatsApp API service provider in Saudi Arabia. Learn how to streamline customer support, automate notifications, leverage rich media messaging, run scalable marketing campaigns, integrate secure payments, synchronize with CRM systems, and ensure enhanced security and privacy.
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...Juraj Vysvader
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I didn't get rich from it but it did have 63K downloads (powered possible tens of thousands of websites).
2. 1. Domain-specific languages
Domain modelling and DSLs
What makes a (good) DSL?
Examples
2. Language Oriented Programming
Playing with a real-world DSL
Discuss the techniques used
Language Oriented Programming
3. Type-safe embedding
Embedding techniques
Type-safety for DSLs
A DSL for validating business rules
4. Da Capo al Coda
A DSL for chatbots with indexed monads
Modifying the chatbot DSL
Wrap-up and conclusion
16. data Syntax = ...
semantics :: Syntax -> _
DSL ≝ model + syntax + semantics
17. data Expr -- Abstract Syntax Tree
= Val Bool
| And Expr Expr
| Or Expr Expr
| Bla Expr
eval :: Expr -> Bool
eval (Val x) = x
eval (And a b) = eval a && eval b
eval (Or a b) = eval a || eval b
eval (Bla a) = not (eval a)
DSL ≝ model + syntax + semantics
18. DSL ≝ model + syntax + semantics
print :: Expr -> String
print (Val x) = show x
print (And a b) = "(" ++ print a ++ " ∧ " ++ print b ++ ")"
print (Or a b) = "(" ++ print a ++ " ∨ " ++ print b ++ ")"
print (Bla a) = "¬" ++ print a
data Expr
= Val Bool
| And Expr Expr
| Or Expr Expr
| Bla Expr
26. A good DSL
Expresses problems using a specific vocabulary
Gives us simple, composable words
Lets us build up larger and correct systems
“in our own words”
27. Why?
To make things simple
To make things pretty
To make things fast
To make things correct
Any combination of the above
30. recipe :: Parser Recipe
recipe = do
rn <- lexeme stringLike
lexeme (syntacticSugar "is made with") *> string "rn"
i <- many1 ingredient
many1 (string "rn")
lexeme (string "prepared by") *> string "rn"
s <- many1 step
return $ Recipe rn i s
https://www.schoolofhaskell.com/user/adinapoli/the-pragmatic-haskeller/episode-5-a-simple-dsl
31. mySpec :: Spec
mySpec = do
describe "Prelude.head" $ do
it "returns the first element of a list" $ do
head [23 ..] `shouldBe` (23 :: Int)
it "returns the first element of an *arbitrary* list" $ do
property $ x xs ->
head (x:xs) == (x :: Int)
it "throws an exception if used with an empty list" $ do
evaluate (head []) `shouldThrow` anyException
https://hspec.github.io/
32. share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persist|
Person
name String
age Int Maybe
deriving Eq Show
BlogPost
title String
authorId PersonId
deriving Eq Show
Follow
follower PersonId
followed PersonId
deriving Eq Show
|] https://www.yesodweb.com/book/persistent
33. recentArticles :: SqlPersistT m [(Entity User, Entity Article)]
recentArticles =
select . from $ (users `InnerJoin` articles) -> do
on (users ^.UserId ==. articles ^.ArticleAuthorId)
orderBy [desc (articles ^.ArticlePublishedTime)]
limit 10
return (users, articles)
https://mmhaskell.com/web-skills-5
34. type UserAPI
= "users"
:> ReqBody '[JSON] User
:> Post '[JSON] User
:<|>
"users"
:> Capture "userId" Integer
:> ReqBody '[JSON] User
:> Put '[JSON] User
https://docs.servant.dev/en/stable/tutorial/ApiType.html
35. type UserAPI
= "users"
( ReqBody '[JSON] User
:> Post '[JSON] User
:<|>
Capture "userId" Integer
:> ReqBody '[JSON] User
:> Put '[JSON] User
)
https://docs.servant.dev/en/stable/tutorial/ApiType.html
36. “If you have a set of things and a means of combining them,
then it’s a language.”
https://parametri.city/blog/2018-12-23-language-oriented-software-engineering
52. indent
:: forall props value result
. String
-> RequiredField
-> FormBuilder props value result
-> FormBuilder props value result
focus
:: forall props s a result
. Lens' s a
-> FormBuilder props a result
-> FormBuilder props s result
53. validated
:: forall props value result_ result
. (result_ -> Either String result)
-> FormBuilder props value result_
-> FormBuilder props (Validated value) result
withValue
:: forall props value result
. (value -> FormBuilder props value result)
-> FormBuilder props value result
54. build
:: forall props value result
. FormBuilder props value result
-> { value :: value
, onChange :: (value -> value) -> Effect Unit
| props
}
-> JSX
revalidate
:: forall props value result
. FormBuilder props value result
-> props
-> value
-> Maybe result
57. newtype Wizard props value result =
Wizard
(Free (FormBuilder props value) result)
derive newtype instance Monad (Wizard props value)
step
:: forall props value result
. FormBuilder props value result
-> Wizard props value result
58. newtype TableFormBuilder props value result = ...
instance Applicative (TableFormBuilder props value)
column
:: forall props row result
. String
-> FormBuilder props row result
-> TableFormBuilder props row result
table
:: forall props row result
. TableFormBuilder props row result
-> FormBuilder props (Array row) (Array result)
60. Language oriented programming
Design a domain-specific language for the core
application logic
Write the application in the DSL
Build interpreters to execute the DSL programs
61. Language oriented programming
Abstracting business problems as programming
language problems, so that solutions are DSLs
How to abstract things ⇔ how to split things up
and join them back together
70. Shallow × deep embedding
Who does the work, interpreters or constructors?
Extending: new interpretations or new constructors?
Deep is simple, but shallow is direct
71. newtype FormBuilder props value result = FormBuilder
( props
-> value
-> { edit :: ((value -> value) -> Effect Unit) -> UI
, validate :: Maybe result
}
)
Shallow embedding
72. Shallow embedding
Syntax is defined in terms of the semantic domain
More flexibility for adding new combinators
(under a specific interpretation)
Adding a new interpreter might imply:
● adding some new set of constructors
● and/or refactoring the semantic domain to include the new
interpretation, then rework all constructors
73. data FormBuilder props value result where
Textbox :: FormBuilder props String String
Password :: FormBuilder props String String
···
Focus
:: Lens' s a
-> FormBuilder props a result
-> FormBuilder props s result
···
Deep embedding
74. More flexibility for adding new interpreters
(for a specific set of constructors)
Adding new constructors might imply reworking
all interpreters
Deep embedding
75. “[…] The goal is to define a datatype by cases, where one can
add new cases to the datatype and new functions over the
datatype, without recompiling existing code, and while
retaining static type safety.”
https://en.wikipedia.org/wiki/Expression_problemExpression problem
87. data AppConfig = AppConfig
{ hostname :: String
, port :: Int
, emailKey :: String
, emailPassword :: String
, emailDefaultFrom :: Maybe String
}
88. appConfig :: EnvConfig AppConfig
appConfig = do
hostname <- string "hostname"
port <- int "port"
emailKey <- string "emailKey"
emailPassword <- string "emailPassword"
emailDefaultFrom <-
if isJust emailKey then
Just <$> string "emailDefaultFrom"
else
pure Nothing
pure $
AppConfig
{ hostname = hostname
, port = port
, emailKey = emailKey
, emailPassword = emailPassword
, emailDefaultFrom = emailDefaultFrom
}
89. “[…] The goal is to define a datatype by cases, where one can
add new cases to the datatype and new functions over the
datatype, without recompiling existing code, and while
retaining static type safety.”
https://en.wikipedia.org/wiki/Expression_problemExpression problem
92. class Monoid d => MathDoc d where
text :: String -> d
(-) :: d -> d -> d -- subscripting
(^) :: d -> d -> d -- superscripting
(/) :: d -> d -> d -- fraction
http://okmij.org/ftp/tagless-final/MathLayout.hs
93. data LaTeX = LaTeX String
instance Monoid LaTeX ...
instance MathDoc LaTeX where
text = LaTeX
LaTeX a - LaTeX b = LaTeX (a ++ "_{" ++ b ++ "}")
LaTeX a ^ LaTeX b = LaTeX (a ++ "^{" ++ b ++ "}")
LaTeX a / LaTeX b = LaTeX ("frac{" ++ a ++ "}{" ++ b ++ "}")
http://okmij.org/ftp/tagless-final/MathLayout.hs
95. data LaTeX = LaTeX String
instance MathDoc LaTeX where
text = LaTeX
LaTeX a - LaTeX b = LaTeX (a ++ "_{" ++ b ++ "}")
LaTeX a ^ LaTeX b = LaTeX (a ++ "^{" ++ b ++ "}")
LaTeX a / LaTeX b = LaTeX ("frac{" ++ a ++ "}{" ++ b ++ "}")
instance MathDoc String where
text = id
a - b = a ++ "_" ++ b
a ^ b = a ++ "^" ++ b
a / b = a ++ "/" ++ b
http://okmij.org/ftp/tagless-final/MathLayout.hs
96. class MathDoc d where
text :: String -> d
(-) :: d -> d -> d -- subscripting
(^) :: d -> d -> d -- superscripting
(/) :: d -> d -> d -- fraction
data GreekLetter d = GreekLetter Char
alpha = greek $ GreekLetter 'ɑ'
class MathDoc d => Greek d where
greek :: GreekLetter -> d
class MathDoc d => Circle d where
circle :: d
http://okmij.org/ftp/tagless-final/MathLayout.hs
100. Goals
● Validate events in an environment
○ Purchase, registration, product viewing, etc.
● Perform operations after events
○ Sending emails, updating the database, etc.
101. data Registration = Registration
{ firstName :: Text
, lastName :: Text
, email :: EmailAddress
, password :: Password
, country :: Country
}
data User = ...
data BillingInfo = ...
data Purchase = ...
data Product = ...
103. businessRules =
fold
[ to buyProduct validatePurchase
, to register validateRegistration
, to viewProduct validateViewProduct
, ···
, to buyProduct validateUserBilling
, after buyProduct sendPurchaseEmail
, ···
]
where
validatePurchase :: Purchase -> _
···
104. {-# LANGUAGE RebindableSyntax #-}
businessRules = do
to buyProduct validatePurchase
to register validateRegistration
to viewProduct validateViewProduct
···
to buyProduct validateUserBilling
after buyProduct sendPurchaseEmail
···
where
(>>) = (<>)
validatePurchase :: Purchase -> _
···
105. validatePurchase purchase = do
user <- authenticate
is
(available
(orderedQuantity `of_` purchase)
(orderedProduct `of_` purchase))
exists (price `of_` orderedProduct `of_` purchase)
exists (country `of_` user
done
where
available q product = quantity `of_` product >= q
validateUserBilling _ = do
user <- authenticate
exists (billingInfo `of_` user)
done
authenticate = do
env <- getEnv
exists (envUser env)
107. Let’s first think about the constraints
1. Validation rules depend on an environment.
2. Validation rules are sequentially composable.
3. Business rules can be combined.
4. The input to a validation rule or to an effect after
an event must match the event’s contents.
5. Dispatching an event to a set of business rules
must give us back (maybe) an effect.
109. type Match f a = f -> Maybe a
to :: Match event e -> (e -> Rules) -> Rules
after :: Match event e -> (env -> e -> m a) -> Rules
dispatch :: Applicative m => Rules -> env -> event -> Maybe (m ())
110. is :: Bool -> Validation ()
exists :: Maybe a -> Validation a
getEnv :: Validation env
runValidation :: Validation a -> env -> Maybe a
-- Syntax sugar
infixr 9 `of_`
of_ :: (a -> b) -> a -> b
of_ = ($)
done :: Monad m => m ()
done = return ()
111. What if we wanted to depend on a database to
perform validations?
What if we wanted to add proper error messages?
Try expressing rules with both deep and shallow
embedding.
What if we wanted to have a pipeline instead?
That is, feeding validated outputs to after rules.
Tip: one possible solution requires having only a single type of
rule instead of the original two: to and after.
Exercises
112. Can we refactor Validation to be written in terms
of classic monad transformers?
How could we statically render validation rules as
documentation text?
How can we restrict the type of effects that can be
performed after each event?
Tip: you can either use records of effects or ConstraintKinds.
Food for thought
118. class IxFunctor f where
imap :: (a -> b) -> f x y a -> f x y b
class IxFunctor m => IxApplicative m where
iapply :: m x y (a -> b) -> m y z a -> m x z b
:: m x y a -> m y z b -> m x z (a, b)
ipure :: a -> m x x a
class IxApplicative m => IxMonad m where
ibind :: m x y a -> (a -> m y z b) -> m x z b
119. preferredLanguage = Ix.do
start any
answer "Hey there!"
language <- askPreferences
loop assertPreferences language
answer "Nice!"
finalize
120. preferredLanguage = Ix.do
start any
answer "Which one do you prefer, Haskell or PureScript?"
language <- ask parseLanguage
loop language lang -> Ix.do
if lang == PureScript then
break unit
else Ix.do
answer "Errrr... Which one do you really prefer?"
lang' <- ask parseLanguage
continue lang'
answer "Nice!"
finalize
where
parseLanguage = do
prefers <-
(Haskell <$ match "haskell") <|>
(PureScript <$ match "purescript")
pure { prefers }
122. Exercises
How can we allow multiple consecutive answers and
questions while keeping the initial and final transitions?
How could we make the DSL strictly applicative?
And what implications does this change effectively have?
Tip: we’ll need to add two new combinators.
123. Food for thought
Can you think of a simpler way to express the same DSL?
How would you improve the domain modelling?
How would your changes affect the DSL?
125. Language is the essence of abstraction.
A language can be seen as a pair syntax + semantics.
We can write tiny languages embedded in Haskell
that correctly model a domain.
Wrapping up
126. We can make use of fundamental typeclasses such as
Monoid, Applicative and Monad to embed a
language more ergonomically and safely.
We can define the syntax of a DSL in Haskell in terms
of its abstract syntax or of its semantic domain.
(deep × shallow embedding)
Wrapping up
127. Wrapping up
We can use typeclasses and instances to embed
extendable DSLs in Haskell. (tagless final style)
We can leverage Haskell’s powerful type system to
make our DSLs more expressive and safe.
Creativity is key, but respecting laws is important.
128. Separation of concerns
High development productivity
Highly maintainable design
Less lines of less complex code
⇒ more maintainable code.
Highly portable design
Depending on the choices regarding
embedding techniques.
The good
134. References
Ward, M. P. (1994). Language Oriented Programming.
Van Deursen, A. et al. (2000). Domain-specific languages: An annotated bibliography.
Kiselyov, O. (2012). Typed Tagless Final Interpreters.
Gibbons, J., & Wu, N. (2014). Folding Domain-Specific Languages: Deep and Shallow
Embeddings.