SlideShare a Scribd company logo
1 of 43
1
Functional
Design
Explained
David Sankel - Stellar Science
david@stellarscience.com
CppCon 2015
2
Math Engineering
3Stellar ScienceDavid Sankel
Quiz
Are the following two C++ programs the same?
4Stellar ScienceDavid Sankel
Quiz
Are the following two C++ programs the same?
#include <iostream>
int main( int argc, char** argv )
{
std::cout << “Hello Worldn”;
}
#include <iostream>
int main( int argc, char** argv )
{
std:: cout << “Hello Worldn”;
}
5Stellar ScienceDavid Sankel
Quiz
Are the following two programs the same?
#include <iostream>
int main( int argc, char** argv )
{
std::cout << “Hello Worldn”;
}
#!/usr/bin/env python
print(“Hello World”)
6Stellar ScienceDavid Sankel
Quiz
Are the following two programs the same?
int f( int c )
{
if( false )
return 45;
else
return c + 5;
}
int f( int c )
{
int j = 5;
j += c;
return j;
}
7Stellar ScienceDavid Sankel
Essence of Programs
Ideally we would like:
• Strong equivalence properties
• Something written down
• A set of rules we can apply to any program
Any ideas of what would be a good essence language?
8Stellar ScienceDavid Sankel
How about math?
3 + 2 = 5
5 = 3 + 2
9Stellar ScienceDavid Sankel
Denotational Semantics
Developed by Dana Scott and Christopher Strachey in late 1960s
Write a mathematical function to convert syntax to meaning (in
math).
μ⟦e₁ + e₂⟧ = μ⟦e₁ ⟧ + μ⟦e₂⟧ where eᵢ is an expression
μ⟦i⟧ = i where i is an integer
10Stellar ScienceDavid Sankel
What is the meaning of this?
int f( int c )
{
if( false )
return 45;
else
return c + 5;
}
11Stellar ScienceDavid Sankel
Function Meaning
We could represent a
function as a set of pairs
As in:
{ …,(-1,4), (0,5), (1,6),…}
Or as a lambda equation: λc. c + 5
Or something else: f(c) = c + 5
int f( int c )
{
if( false )
return 45;
else
return c + 5;
}
12Stellar ScienceDavid Sankel
Function Meaning
What about this?
int f( int c )
{
for(;;) ;
return 45;
}
…,(-1, ⊥),(0,⊥),(1, ⊥),…
⊥ is “bottom”
13Stellar ScienceDavid Sankel
The Next 700 Programming
Languages
P. J. Landin wrote in 1966 about his programming language
ISWIM (If you See What I Mean)
f(b+2c) + f(2b-c)
where f(x) = x(x+a)
14Stellar ScienceDavid Sankel
Why not drop the C++
nonsense and go Haskell?
Haskell variant with optimizations: 0.41s
C++ variant without optimizations: 0.16s
0
0.2
0.4
0.6
Haskell C++
Quicksort 160,000 ints
15Stellar ScienceDavid Sankel
Languages and Machines
16Stellar ScienceDavid Sankel
Semantics Discovery
• Discover the mathematical essence of
a problem and derive an
implementation.
• Conal Elliott, various applications of
semantics discovery throughout career.
• See ‘Denotational design with type
class morphisms’.
17Stellar ScienceDavid Sankel
Ingredients
• Math augmented with some extra constructs can represent
the essence of code.
• Write programs in math.
• C++ straddles more levels of abstraction than any other
language.
• Discover essence of problem using math and derive
implementation.
18Stellar ScienceDavid Sankel
Functional Design
1. Discover the mathematical essence of the problem and write
it out.
2. Derive an efficient implementation in C++ that has the
interface discovered in #1.
19Stellar ScienceDavid Sankel
Algebraic Data Types
• Mathematical fundamentals of base types.
• Two types, 1 and 0
• Two ops, ⊕ and ⊗, to compose them
20Stellar ScienceDavid Sankel
0 Type
0 is the type with no values
struct Zero {
Zero() = delete;
};
21Stellar ScienceDavid Sankel
1 Type
1 is the type with one value
struct One {};
22Stellar ScienceDavid Sankel
Product
Given types ‘a’ and ‘b’, the product of ‘a’ and ‘b’ (a ⊗ b) is a type
whose values have an ‘a’ and a ‘b’.
using AAndB = std::pair<A,B>;
using AAndB = std::tuple<A,B>;
struct AAndB {
A a;
B b;
};
23Stellar ScienceDavid Sankel
Product
Is this an implementation of a ⊗ b?
struct AAndB {
std::unique_ptr<A> a;
std::unique_ptr<B> b;
};
24Stellar ScienceDavid Sankel
Sum
A ⊕ B is a type whose values are either a value of type ‘A’ or a value of type
‘B’.
struct AOrB {
bool hasA;
union {
A a;
B b;
} contents; // ‘a’ when ‘hasA==true’
// otherwise ‘b’.
};
using AOrB = boost::variant< A, B >;
using AOrB = std::variant< A, B >; // hopefully
25Stellar ScienceDavid Sankel
Function Type
A → B is a type whose values are pure functions with an input
type A and an return type B.
using FunctionAB = std::function<B (A)>;
26Stellar ScienceDavid Sankel
Meaning
μ⟦ syntax ⟧ = mathExpression
The meaning of “syntax” is the math expression
μ⟦ expression ⟧ : mathExpression
The type of “expression” is the math expression
μ⟦ int ⟧ = ℤ
μ⟦ 3 ⟧ : ℤ
μ⟦ 3 ⟧ = 3
27Stellar ScienceDavid Sankel
Some Examples
μ⟦ boost::optional<e₁> ⟧ = μ⟦ e₁ ⟧ ⊕ 1
μ⟦ std::pair<e₁,e₂> ⟧ = μ⟦ e₁ ⟧ ⊗ μ⟦ e₂ ⟧
μ⟦ double ⟧ = ℝ
or maybe
μ⟦ double ⟧ = ℝ ⊕ 1⊕ 1⊕ 1
where the extra states are -∞, +∞, and NaN
28Stellar ScienceDavid Sankel
What is a movie?
29Stellar ScienceDavid Sankel
What is a movie?
μ⟦ Movie<e> ⟧ = ℝ → μ⟦ e ⟧
Operations:
μ⟦ always<e> ⟧ : μ⟦ e ⟧ → μ⟦ Movie<e> ⟧
μ⟦ always<e>(a) ⟧ = λ t. μ⟦ a ⟧
μ⟦ snapshot<e> ⟧ : μ⟦Movie<e>⟧ → ℝ → A
μ⟦ snapshot<e>(movie, time) ⟧ = μ⟦ movie ⟧ ( μ⟦ time ⟧ )
μ⟦ transform<A,B> ⟧ : (μ⟦A⟧ → μ⟦B⟧) → μ⟦Movie<A>⟧ → μ⟦Movie<B>⟧
μ⟦ timeMovie ⟧ : μ⟦ Movie<double> ⟧
μ⟦ timeMovie ⟧ = λ t. t
30Stellar ScienceDavid Sankel
Grey flux movie
auto greyFluxMovie = transform(
[]( double timeInSeconds ) -> Image {
double dummy;
double greyness = std::modf( timeInSeconds, &dummy );
return greyImage( greyness );
, time );
31Stellar ScienceDavid Sankel
What is a stream?
32Stellar ScienceDavid Sankel
What is a stream?
Let ‘Action’ be some side-effecting operation.
μ⟦ sink<e> ⟧ = μ⟦ e ⟧ → Action
μ⟦ source<e> ⟧ = (μ⟦ e ⟧ → Action) → Action
template< typename T >
using sink = std::function<void ( const T & )>;
template< typename T >
using source = std::function<void ( sink<T> ) >;
33Stellar ScienceDavid Sankel
Example source/sink
source<char> consoleInput = []( sink<char> s ) {
int inputChar;
while( (inputChar = std::cin.get()) != EOF ) {
s( static_cast< char >( inputChar ) );
};
sink<char> consoleOutput = []( char c ) {
std::cout.put( c );
};
34Stellar ScienceDavid Sankel
Connecting Sources and Sinks
μ⟦ connect<e> ⟧ : μ⟦ source<e> ⟧ → μ⟦ sink<e> ⟧ → Action
μ⟦ connect<e>( so, si ) ⟧ = μ⟦ so ⟧( μ⟦ si ⟧ )
template< typename t >
void connect( source<t> so, sink<t> si ) {
so( si );
}
int main( int argc, char** argv ) {
connect( consoleInput, consoleOutput );
}
35Stellar ScienceDavid Sankel
Transforming Streams
μ⟦ sink<e> ⟧ = μ⟦ e ⟧ → Action
μ⟦ transform<a,b> ⟧ = μ⟦ Sink<b> ⟧ → μ⟦ Sink<a> ⟧
= μ⟦ Sink<b> ⟧ → (μ⟦ a ⟧ → Action)
= μ⟦ Sink<b> ⟧ → μ⟦ a ⟧ → Action
template< typename a, typename b >
using transform = std::function<void ( sink<b>, a ) >;
36Stellar ScienceDavid Sankel
Application of Transforms
μ⟦ transform<a,b> ⟧ = μ⟦ sink<b> ⟧ → μ⟦ a ⟧ → Action
μ⟦ applyToSink<a,b> ⟧
: μ⟦ transform<a,b> ⟧ → μ⟦ sink<b> ⟧ → μ⟦ sink<a> ⟧
μ⟦ applyToSource<a,b> ⟧
: μ⟦ transform<a,b> ⟧ → μ⟦ source<a> ⟧ → μ⟦ source<b> ⟧
μ⟦ so >> t ⟧ = μ⟦ applyToSource<a,b> ⟧( t, so );
μ⟦ t >> si ⟧ = μ⟦ applyToSink<a,b> ⟧( t, si );
μ⟦ so >> si ⟧ = μ⟦ connect<t> ⟧( so, si );
37Stellar ScienceDavid Sankel
Tranformers Continued…
transformer<char, std::string> getLines = //…
transformer<std::string, char> unWords = //…
source<string> inputLines = consoleInput >> getLines;
sink<string> wordOutput = unwords >> consoleOutput;
InputLines >> wordOutput;
transformer<char,char> linesToSpaces = getLines >> unwords;
38Stellar ScienceDavid Sankel
What is command line
processing?
39Stellar ScienceDavid Sankel
What is command line
processing?
μ⟦ CommandLineProcessor<a> ⟧ = ListOf String → μ⟦ a ⟧ ?
Hrm…
μ⟦ Parser<a,b> ⟧ = ListOf μ⟦ a ⟧ → μ⟦ b ⟧
μ⟦ CommandLineProcessor<a> ⟧ = μ⟦ Parser<String,b> ⟧
40Stellar ScienceDavid Sankel
Command Line Parsing
struct HelpFlag{};
struct UserFlag{
std::string user;
};
auto flagP = mix(
args(“--help”, HelpFlag()),
args(“--user“ >> stringP,
[]( std::string username ) { return UserFlag{username}; })
41Stellar ScienceDavid Sankel
Command Line Parsing
struct ListAccounts {};
struct ListJob {
int jobId;
};
struct CommandLineParse {
std::vector< boost::variant< HelpFlag, UserFlag > > globalFlags;
boost::variant< ListAccounts, ListJob > mode;
};
auto parser = flagP
>> (args( “listAccounts”, ListAccounts() ) ||
(args( “listJob” ) >> “--jobId” >> intP( []( int id ) { return ListJob{id};}));
42Stellar ScienceDavid Sankel
Benefits
• Highly Flexible
• Highly Composible
• Type safe
• Simple
43Stellar ScienceDavid Sankel
Functional
Design
1. Discover the essence
2. Derive the
implementation
• Beautiful API’s
• Screaming Speed
david@stellarscience.com

More Related Content

What's hot

Beauty and the beast - Haskell on JVM
Beauty and the beast  - Haskell on JVMBeauty and the beast  - Haskell on JVM
Beauty and the beast - Haskell on JVMJarek Ratajski
 
Data Structures Practical File
Data Structures Practical File Data Structures Practical File
Data Structures Practical File Harjinder Singh
 
Queue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked ListQueue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked ListPTCL
 
The present and the future of functional programming in c++
The present and the future of functional programming in c++The present and the future of functional programming in c++
The present and the future of functional programming in c++Alexander Granin
 
SE Computer, Programming Laboratory(210251) University of Pune
SE Computer, Programming Laboratory(210251) University of PuneSE Computer, Programming Laboratory(210251) University of Pune
SE Computer, Programming Laboratory(210251) University of PuneBhavesh Shah
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Leonardo Borges
 
High performance web programming with C++14
High performance web programming with C++14High performance web programming with C++14
High performance web programming with C++14Matthieu Garrigues
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class PatternsJohn De Goes
 
Introduction to functional programming using Ocaml
Introduction to functional programming using OcamlIntroduction to functional programming using Ocaml
Introduction to functional programming using Ocamlpramode_ce
 
Computer graphics lab manual
Computer graphics lab manualComputer graphics lab manual
Computer graphics lab manualUma mohan
 
"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)
"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)
"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)AvitoTech
 
Machine-level Composition of Modularized Crosscutting Concerns
Machine-level Composition of Modularized Crosscutting ConcernsMachine-level Composition of Modularized Crosscutting Concerns
Machine-level Composition of Modularized Crosscutting Concernssaintiss
 
JavaScript 2016 for C# Developers
JavaScript 2016 for C# DevelopersJavaScript 2016 for C# Developers
JavaScript 2016 for C# DevelopersRick Beerendonk
 
Oops practical file
Oops practical fileOops practical file
Oops practical fileAnkit Dixit
 

What's hot (20)

Beauty and the beast - Haskell on JVM
Beauty and the beast  - Haskell on JVMBeauty and the beast  - Haskell on JVM
Beauty and the beast - Haskell on JVM
 
Struct examples
Struct examplesStruct examples
Struct examples
 
Data Structures Practical File
Data Structures Practical File Data Structures Practical File
Data Structures Practical File
 
Queue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked ListQueue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked List
 
The present and the future of functional programming in c++
The present and the future of functional programming in c++The present and the future of functional programming in c++
The present and the future of functional programming in c++
 
SE Computer, Programming Laboratory(210251) University of Pune
SE Computer, Programming Laboratory(210251) University of PuneSE Computer, Programming Laboratory(210251) University of Pune
SE Computer, Programming Laboratory(210251) University of Pune
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015
 
Monadic parsers in C++
Monadic parsers in C++Monadic parsers in C++
Monadic parsers in C++
 
High performance web programming with C++14
High performance web programming with C++14High performance web programming with C++14
High performance web programming with C++14
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class Patterns
 
Java -lec-5
Java -lec-5Java -lec-5
Java -lec-5
 
Introduction to functional programming using Ocaml
Introduction to functional programming using OcamlIntroduction to functional programming using Ocaml
Introduction to functional programming using Ocaml
 
Computer graphics lab manual
Computer graphics lab manualComputer graphics lab manual
Computer graphics lab manual
 
"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)
"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)
"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)
 
Java Program
Java ProgramJava Program
Java Program
 
Machine-level Composition of Modularized Crosscutting Concerns
Machine-level Composition of Modularized Crosscutting ConcernsMachine-level Composition of Modularized Crosscutting Concerns
Machine-level Composition of Modularized Crosscutting Concerns
 
JavaScript 2016 for C# Developers
JavaScript 2016 for C# DevelopersJavaScript 2016 for C# Developers
JavaScript 2016 for C# Developers
 
Seeing Like Software
Seeing Like SoftwareSeeing Like Software
Seeing Like Software
 
Oops practical file
Oops practical fileOops practical file
Oops practical file
 
C++ file
C++ fileC++ file
C++ file
 

Viewers also liked

Types Don't Know #, Howard Hinnant - CppCon 2014
Types Don't Know #, Howard Hinnant - CppCon 2014Types Don't Know #, Howard Hinnant - CppCon 2014
Types Don't Know #, Howard Hinnant - CppCon 2014Ripple Labs
 
Functional Programming in C++
Functional Programming in C++Functional Programming in C++
Functional Programming in C++sankeld
 
Give me 15 minutes and i'll change your view of gdb
Give me 15 minutes and i'll change your view of gdbGive me 15 minutes and i'll change your view of gdb
Give me 15 minutes and i'll change your view of gdbgregthelaw
 
From Zero to Iterators: Building and Extending the Iterator Hierarchy in a Mo...
From Zero to Iterators: Building and Extending the Iterator Hierarchy in a Mo...From Zero to Iterators: Building and Extending the Iterator Hierarchy in a Mo...
From Zero to Iterators: Building and Extending the Iterator Hierarchy in a Mo...Patrick Niedzielski
 
Cpp17 and Beyond
Cpp17 and BeyondCpp17 and Beyond
Cpp17 and BeyondComicSansMS
 
Anatomy of spark catalyst
Anatomy of spark catalystAnatomy of spark catalyst
Anatomy of spark catalystdatamantra
 
Enhancing Spark SQL Optimizer with Reliable Statistics
Enhancing Spark SQL Optimizer with Reliable StatisticsEnhancing Spark SQL Optimizer with Reliable Statistics
Enhancing Spark SQL Optimizer with Reliable StatisticsJen Aman
 
Credit Fraud Prevention with Spark and Graph Analysis
Credit Fraud Prevention with Spark and Graph AnalysisCredit Fraud Prevention with Spark and Graph Analysis
Credit Fraud Prevention with Spark and Graph AnalysisJen Aman
 
Enhancements on Spark SQL optimizer by Min Qiu
Enhancements on Spark SQL optimizer by Min QiuEnhancements on Spark SQL optimizer by Min Qiu
Enhancements on Spark SQL optimizer by Min QiuSpark Summit
 
Deep Dive into Project Tungsten: Bringing Spark Closer to Bare Metal-(Josh Ro...
Deep Dive into Project Tungsten: Bringing Spark Closer to Bare Metal-(Josh Ro...Deep Dive into Project Tungsten: Bringing Spark Closer to Bare Metal-(Josh Ro...
Deep Dive into Project Tungsten: Bringing Spark Closer to Bare Metal-(Josh Ro...Spark Summit
 
Deep Dive Into Catalyst: Apache Spark 2.0'S Optimizer
Deep Dive Into Catalyst: Apache Spark 2.0'S OptimizerDeep Dive Into Catalyst: Apache Spark 2.0'S Optimizer
Deep Dive Into Catalyst: Apache Spark 2.0'S OptimizerSpark Summit
 

Viewers also liked (11)

Types Don't Know #, Howard Hinnant - CppCon 2014
Types Don't Know #, Howard Hinnant - CppCon 2014Types Don't Know #, Howard Hinnant - CppCon 2014
Types Don't Know #, Howard Hinnant - CppCon 2014
 
Functional Programming in C++
Functional Programming in C++Functional Programming in C++
Functional Programming in C++
 
Give me 15 minutes and i'll change your view of gdb
Give me 15 minutes and i'll change your view of gdbGive me 15 minutes and i'll change your view of gdb
Give me 15 minutes and i'll change your view of gdb
 
From Zero to Iterators: Building and Extending the Iterator Hierarchy in a Mo...
From Zero to Iterators: Building and Extending the Iterator Hierarchy in a Mo...From Zero to Iterators: Building and Extending the Iterator Hierarchy in a Mo...
From Zero to Iterators: Building and Extending the Iterator Hierarchy in a Mo...
 
Cpp17 and Beyond
Cpp17 and BeyondCpp17 and Beyond
Cpp17 and Beyond
 
Anatomy of spark catalyst
Anatomy of spark catalystAnatomy of spark catalyst
Anatomy of spark catalyst
 
Enhancing Spark SQL Optimizer with Reliable Statistics
Enhancing Spark SQL Optimizer with Reliable StatisticsEnhancing Spark SQL Optimizer with Reliable Statistics
Enhancing Spark SQL Optimizer with Reliable Statistics
 
Credit Fraud Prevention with Spark and Graph Analysis
Credit Fraud Prevention with Spark and Graph AnalysisCredit Fraud Prevention with Spark and Graph Analysis
Credit Fraud Prevention with Spark and Graph Analysis
 
Enhancements on Spark SQL optimizer by Min Qiu
Enhancements on Spark SQL optimizer by Min QiuEnhancements on Spark SQL optimizer by Min Qiu
Enhancements on Spark SQL optimizer by Min Qiu
 
Deep Dive into Project Tungsten: Bringing Spark Closer to Bare Metal-(Josh Ro...
Deep Dive into Project Tungsten: Bringing Spark Closer to Bare Metal-(Josh Ro...Deep Dive into Project Tungsten: Bringing Spark Closer to Bare Metal-(Josh Ro...
Deep Dive into Project Tungsten: Bringing Spark Closer to Bare Metal-(Josh Ro...
 
Deep Dive Into Catalyst: Apache Spark 2.0'S Optimizer
Deep Dive Into Catalyst: Apache Spark 2.0'S OptimizerDeep Dive Into Catalyst: Apache Spark 2.0'S Optimizer
Deep Dive Into Catalyst: Apache Spark 2.0'S Optimizer
 

Similar to Functional Design Explained (David Sankel CppCon 2015)

PVS-Studio team experience: checking various open source projects, or mistake...
PVS-Studio team experience: checking various open source projects, or mistake...PVS-Studio team experience: checking various open source projects, or mistake...
PVS-Studio team experience: checking various open source projects, or mistake...Andrey Karpov
 
Best Bugs from Games: Fellow Programmers' Mistakes
Best Bugs from Games: Fellow Programmers' MistakesBest Bugs from Games: Fellow Programmers' Mistakes
Best Bugs from Games: Fellow Programmers' MistakesAndrey Karpov
 
Why learn new programming languages
Why learn new programming languagesWhy learn new programming languages
Why learn new programming languagesJonas Follesø
 
Kyo - Functional Scala 2023.pdf
Kyo - Functional Scala 2023.pdfKyo - Functional Scala 2023.pdf
Kyo - Functional Scala 2023.pdfFlavio W. Brasil
 
Scala as a Declarative Language
Scala as a Declarative LanguageScala as a Declarative Language
Scala as a Declarative Languagevsssuresh
 
Dynamic C++ Silicon Valley Code Camp 2012
Dynamic C++ Silicon Valley Code Camp 2012Dynamic C++ Silicon Valley Code Camp 2012
Dynamic C++ Silicon Valley Code Camp 2012aleks-f
 
LAC2013 UNIT preTESTs!
LAC2013 UNIT preTESTs!LAC2013 UNIT preTESTs!
LAC2013 UNIT preTESTs!A Jorge Garcia
 
Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»SpbDotNet Community
 
01. introduction to C++
01. introduction to C++01. introduction to C++
01. introduction to C++Haresh Jaiswal
 
Community-driven Language Design at TC39 on the JavaScript Pipeline Operator ...
Community-driven Language Design at TC39 on the JavaScript Pipeline Operator ...Community-driven Language Design at TC39 on the JavaScript Pipeline Operator ...
Community-driven Language Design at TC39 on the JavaScript Pipeline Operator ...Igalia
 
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...DevGAMM Conference
 
Robust Operations of Kafka Streams
Robust Operations of Kafka StreamsRobust Operations of Kafka Streams
Robust Operations of Kafka Streamsconfluent
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsMichael Pirnat
 
High-Performance Haskell
High-Performance HaskellHigh-Performance Haskell
High-Performance HaskellJohan Tibell
 
視覚化とSwiftのタイプについて
視覚化とSwiftのタイプについて視覚化とSwiftのタイプについて
視覚化とSwiftのタイプについてRay Fix
 

Similar to Functional Design Explained (David Sankel CppCon 2015) (20)

PVS-Studio team experience: checking various open source projects, or mistake...
PVS-Studio team experience: checking various open source projects, or mistake...PVS-Studio team experience: checking various open source projects, or mistake...
PVS-Studio team experience: checking various open source projects, or mistake...
 
Best Bugs from Games: Fellow Programmers' Mistakes
Best Bugs from Games: Fellow Programmers' MistakesBest Bugs from Games: Fellow Programmers' Mistakes
Best Bugs from Games: Fellow Programmers' Mistakes
 
Why learn new programming languages
Why learn new programming languagesWhy learn new programming languages
Why learn new programming languages
 
Kyo - Functional Scala 2023.pdf
Kyo - Functional Scala 2023.pdfKyo - Functional Scala 2023.pdf
Kyo - Functional Scala 2023.pdf
 
Scala as a Declarative Language
Scala as a Declarative LanguageScala as a Declarative Language
Scala as a Declarative Language
 
C# 8 and Beyond
C# 8 and BeyondC# 8 and Beyond
C# 8 and Beyond
 
Dynamic C++ Silicon Valley Code Camp 2012
Dynamic C++ Silicon Valley Code Camp 2012Dynamic C++ Silicon Valley Code Camp 2012
Dynamic C++ Silicon Valley Code Camp 2012
 
Lecture6
Lecture6Lecture6
Lecture6
 
Muzzammilrashid
MuzzammilrashidMuzzammilrashid
Muzzammilrashid
 
LAC2013 UNIT preTESTs!
LAC2013 UNIT preTESTs!LAC2013 UNIT preTESTs!
LAC2013 UNIT preTESTs!
 
Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»
 
01. introduction to C++
01. introduction to C++01. introduction to C++
01. introduction to C++
 
CppTutorial.ppt
CppTutorial.pptCppTutorial.ppt
CppTutorial.ppt
 
Community-driven Language Design at TC39 on the JavaScript Pipeline Operator ...
Community-driven Language Design at TC39 on the JavaScript Pipeline Operator ...Community-driven Language Design at TC39 on the JavaScript Pipeline Operator ...
Community-driven Language Design at TC39 on the JavaScript Pipeline Operator ...
 
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
 
Robust Operations of Kafka Streams
Robust Operations of Kafka StreamsRobust Operations of Kafka Streams
Robust Operations of Kafka Streams
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) Things
 
High-Performance Haskell
High-Performance HaskellHigh-Performance Haskell
High-Performance Haskell
 
Cpp tutorial
Cpp tutorialCpp tutorial
Cpp tutorial
 
視覚化とSwiftのタイプについて
視覚化とSwiftのタイプについて視覚化とSwiftのタイプについて
視覚化とSwiftのタイプについて
 

Recently uploaded

Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 

Recently uploaded (20)

Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 

Functional Design Explained (David Sankel CppCon 2015)

  • 1. 1 Functional Design Explained David Sankel - Stellar Science david@stellarscience.com CppCon 2015
  • 3. 3Stellar ScienceDavid Sankel Quiz Are the following two C++ programs the same?
  • 4. 4Stellar ScienceDavid Sankel Quiz Are the following two C++ programs the same? #include <iostream> int main( int argc, char** argv ) { std::cout << “Hello Worldn”; } #include <iostream> int main( int argc, char** argv ) { std:: cout << “Hello Worldn”; }
  • 5. 5Stellar ScienceDavid Sankel Quiz Are the following two programs the same? #include <iostream> int main( int argc, char** argv ) { std::cout << “Hello Worldn”; } #!/usr/bin/env python print(“Hello World”)
  • 6. 6Stellar ScienceDavid Sankel Quiz Are the following two programs the same? int f( int c ) { if( false ) return 45; else return c + 5; } int f( int c ) { int j = 5; j += c; return j; }
  • 7. 7Stellar ScienceDavid Sankel Essence of Programs Ideally we would like: • Strong equivalence properties • Something written down • A set of rules we can apply to any program Any ideas of what would be a good essence language?
  • 8. 8Stellar ScienceDavid Sankel How about math? 3 + 2 = 5 5 = 3 + 2
  • 9. 9Stellar ScienceDavid Sankel Denotational Semantics Developed by Dana Scott and Christopher Strachey in late 1960s Write a mathematical function to convert syntax to meaning (in math). μ⟦e₁ + e₂⟧ = μ⟦e₁ ⟧ + μ⟦e₂⟧ where eᵢ is an expression μ⟦i⟧ = i where i is an integer
  • 10. 10Stellar ScienceDavid Sankel What is the meaning of this? int f( int c ) { if( false ) return 45; else return c + 5; }
  • 11. 11Stellar ScienceDavid Sankel Function Meaning We could represent a function as a set of pairs As in: { …,(-1,4), (0,5), (1,6),…} Or as a lambda equation: λc. c + 5 Or something else: f(c) = c + 5 int f( int c ) { if( false ) return 45; else return c + 5; }
  • 12. 12Stellar ScienceDavid Sankel Function Meaning What about this? int f( int c ) { for(;;) ; return 45; } …,(-1, ⊥),(0,⊥),(1, ⊥),… ⊥ is “bottom”
  • 13. 13Stellar ScienceDavid Sankel The Next 700 Programming Languages P. J. Landin wrote in 1966 about his programming language ISWIM (If you See What I Mean) f(b+2c) + f(2b-c) where f(x) = x(x+a)
  • 14. 14Stellar ScienceDavid Sankel Why not drop the C++ nonsense and go Haskell? Haskell variant with optimizations: 0.41s C++ variant without optimizations: 0.16s 0 0.2 0.4 0.6 Haskell C++ Quicksort 160,000 ints
  • 16. 16Stellar ScienceDavid Sankel Semantics Discovery • Discover the mathematical essence of a problem and derive an implementation. • Conal Elliott, various applications of semantics discovery throughout career. • See ‘Denotational design with type class morphisms’.
  • 17. 17Stellar ScienceDavid Sankel Ingredients • Math augmented with some extra constructs can represent the essence of code. • Write programs in math. • C++ straddles more levels of abstraction than any other language. • Discover essence of problem using math and derive implementation.
  • 18. 18Stellar ScienceDavid Sankel Functional Design 1. Discover the mathematical essence of the problem and write it out. 2. Derive an efficient implementation in C++ that has the interface discovered in #1.
  • 19. 19Stellar ScienceDavid Sankel Algebraic Data Types • Mathematical fundamentals of base types. • Two types, 1 and 0 • Two ops, ⊕ and ⊗, to compose them
  • 20. 20Stellar ScienceDavid Sankel 0 Type 0 is the type with no values struct Zero { Zero() = delete; };
  • 21. 21Stellar ScienceDavid Sankel 1 Type 1 is the type with one value struct One {};
  • 22. 22Stellar ScienceDavid Sankel Product Given types ‘a’ and ‘b’, the product of ‘a’ and ‘b’ (a ⊗ b) is a type whose values have an ‘a’ and a ‘b’. using AAndB = std::pair<A,B>; using AAndB = std::tuple<A,B>; struct AAndB { A a; B b; };
  • 23. 23Stellar ScienceDavid Sankel Product Is this an implementation of a ⊗ b? struct AAndB { std::unique_ptr<A> a; std::unique_ptr<B> b; };
  • 24. 24Stellar ScienceDavid Sankel Sum A ⊕ B is a type whose values are either a value of type ‘A’ or a value of type ‘B’. struct AOrB { bool hasA; union { A a; B b; } contents; // ‘a’ when ‘hasA==true’ // otherwise ‘b’. }; using AOrB = boost::variant< A, B >; using AOrB = std::variant< A, B >; // hopefully
  • 25. 25Stellar ScienceDavid Sankel Function Type A → B is a type whose values are pure functions with an input type A and an return type B. using FunctionAB = std::function<B (A)>;
  • 26. 26Stellar ScienceDavid Sankel Meaning μ⟦ syntax ⟧ = mathExpression The meaning of “syntax” is the math expression μ⟦ expression ⟧ : mathExpression The type of “expression” is the math expression μ⟦ int ⟧ = ℤ μ⟦ 3 ⟧ : ℤ μ⟦ 3 ⟧ = 3
  • 27. 27Stellar ScienceDavid Sankel Some Examples μ⟦ boost::optional<e₁> ⟧ = μ⟦ e₁ ⟧ ⊕ 1 μ⟦ std::pair<e₁,e₂> ⟧ = μ⟦ e₁ ⟧ ⊗ μ⟦ e₂ ⟧ μ⟦ double ⟧ = ℝ or maybe μ⟦ double ⟧ = ℝ ⊕ 1⊕ 1⊕ 1 where the extra states are -∞, +∞, and NaN
  • 29. 29Stellar ScienceDavid Sankel What is a movie? μ⟦ Movie<e> ⟧ = ℝ → μ⟦ e ⟧ Operations: μ⟦ always<e> ⟧ : μ⟦ e ⟧ → μ⟦ Movie<e> ⟧ μ⟦ always<e>(a) ⟧ = λ t. μ⟦ a ⟧ μ⟦ snapshot<e> ⟧ : μ⟦Movie<e>⟧ → ℝ → A μ⟦ snapshot<e>(movie, time) ⟧ = μ⟦ movie ⟧ ( μ⟦ time ⟧ ) μ⟦ transform<A,B> ⟧ : (μ⟦A⟧ → μ⟦B⟧) → μ⟦Movie<A>⟧ → μ⟦Movie<B>⟧ μ⟦ timeMovie ⟧ : μ⟦ Movie<double> ⟧ μ⟦ timeMovie ⟧ = λ t. t
  • 30. 30Stellar ScienceDavid Sankel Grey flux movie auto greyFluxMovie = transform( []( double timeInSeconds ) -> Image { double dummy; double greyness = std::modf( timeInSeconds, &dummy ); return greyImage( greyness ); , time );
  • 32. 32Stellar ScienceDavid Sankel What is a stream? Let ‘Action’ be some side-effecting operation. μ⟦ sink<e> ⟧ = μ⟦ e ⟧ → Action μ⟦ source<e> ⟧ = (μ⟦ e ⟧ → Action) → Action template< typename T > using sink = std::function<void ( const T & )>; template< typename T > using source = std::function<void ( sink<T> ) >;
  • 33. 33Stellar ScienceDavid Sankel Example source/sink source<char> consoleInput = []( sink<char> s ) { int inputChar; while( (inputChar = std::cin.get()) != EOF ) { s( static_cast< char >( inputChar ) ); }; sink<char> consoleOutput = []( char c ) { std::cout.put( c ); };
  • 34. 34Stellar ScienceDavid Sankel Connecting Sources and Sinks μ⟦ connect<e> ⟧ : μ⟦ source<e> ⟧ → μ⟦ sink<e> ⟧ → Action μ⟦ connect<e>( so, si ) ⟧ = μ⟦ so ⟧( μ⟦ si ⟧ ) template< typename t > void connect( source<t> so, sink<t> si ) { so( si ); } int main( int argc, char** argv ) { connect( consoleInput, consoleOutput ); }
  • 35. 35Stellar ScienceDavid Sankel Transforming Streams μ⟦ sink<e> ⟧ = μ⟦ e ⟧ → Action μ⟦ transform<a,b> ⟧ = μ⟦ Sink<b> ⟧ → μ⟦ Sink<a> ⟧ = μ⟦ Sink<b> ⟧ → (μ⟦ a ⟧ → Action) = μ⟦ Sink<b> ⟧ → μ⟦ a ⟧ → Action template< typename a, typename b > using transform = std::function<void ( sink<b>, a ) >;
  • 36. 36Stellar ScienceDavid Sankel Application of Transforms μ⟦ transform<a,b> ⟧ = μ⟦ sink<b> ⟧ → μ⟦ a ⟧ → Action μ⟦ applyToSink<a,b> ⟧ : μ⟦ transform<a,b> ⟧ → μ⟦ sink<b> ⟧ → μ⟦ sink<a> ⟧ μ⟦ applyToSource<a,b> ⟧ : μ⟦ transform<a,b> ⟧ → μ⟦ source<a> ⟧ → μ⟦ source<b> ⟧ μ⟦ so >> t ⟧ = μ⟦ applyToSource<a,b> ⟧( t, so ); μ⟦ t >> si ⟧ = μ⟦ applyToSink<a,b> ⟧( t, si ); μ⟦ so >> si ⟧ = μ⟦ connect<t> ⟧( so, si );
  • 37. 37Stellar ScienceDavid Sankel Tranformers Continued… transformer<char, std::string> getLines = //… transformer<std::string, char> unWords = //… source<string> inputLines = consoleInput >> getLines; sink<string> wordOutput = unwords >> consoleOutput; InputLines >> wordOutput; transformer<char,char> linesToSpaces = getLines >> unwords;
  • 38. 38Stellar ScienceDavid Sankel What is command line processing?
  • 39. 39Stellar ScienceDavid Sankel What is command line processing? μ⟦ CommandLineProcessor<a> ⟧ = ListOf String → μ⟦ a ⟧ ? Hrm… μ⟦ Parser<a,b> ⟧ = ListOf μ⟦ a ⟧ → μ⟦ b ⟧ μ⟦ CommandLineProcessor<a> ⟧ = μ⟦ Parser<String,b> ⟧
  • 40. 40Stellar ScienceDavid Sankel Command Line Parsing struct HelpFlag{}; struct UserFlag{ std::string user; }; auto flagP = mix( args(“--help”, HelpFlag()), args(“--user“ >> stringP, []( std::string username ) { return UserFlag{username}; })
  • 41. 41Stellar ScienceDavid Sankel Command Line Parsing struct ListAccounts {}; struct ListJob { int jobId; }; struct CommandLineParse { std::vector< boost::variant< HelpFlag, UserFlag > > globalFlags; boost::variant< ListAccounts, ListJob > mode; }; auto parser = flagP >> (args( “listAccounts”, ListAccounts() ) || (args( “listJob” ) >> “--jobId” >> intP( []( int id ) { return ListJob{id};}));
  • 42. 42Stellar ScienceDavid Sankel Benefits • Highly Flexible • Highly Composible • Type safe • Simple
  • 43. 43Stellar ScienceDavid Sankel Functional Design 1. Discover the essence 2. Derive the implementation • Beautiful API’s • Screaming Speed david@stellarscience.com

Editor's Notes

  1. The designs that produced with the methodology we will develop, will not only be simple and concise, but they’ll approach a purity where you start to wonder if you’re getting close to an optimal design.
  2. Here although the individual files are different, the syntax tree is the same. We have syntactic equivalence.
  3. The one on the right is Python. Note that python outputs a newline with every print statement. These are not syntactically equivalent. We can say they are the same because ‘diff’ says the output of these two programs is the same.
  4. Clearly not syntactically equivalent. Neither of these programs have output we can compare using diff. Here we make a mental representation of both of these programs. That mental representation has the strong equivalence property. We mentally remove the extraneous noise. We check that and give an answer. That won’t help convince someone else of the equivalence though. It would be really nice if we could write down this intermediate format.
  5. Hint: you learned this language in grade school.
  6. All of these have the strong equality guarantee provided by math.
  7. We can come up with math that defines how bottom interacts with everything else. A bottom statement followed by another statement has a meaning of bottom, etc. We see that there is an art here to extending the math used in the “semantic domain” to capture
  8. The idea here was to make a programming language based on mathematical notation. Note how Haskell is the modern offspring of this idea that all the kids are using these days. Comment about how ‘monads’ ‘monoids’ ‘categories’, etc. are essential to Haskell’s roots of an attempt to be a mathematics computer language. Also interesting how Landin called his language “see what I mean” before Scott Strachey’s rigorous definition of meaning.
  9. I just asked google for an implementation of each and ran them on 160,000 ints. Can the Haskell version be optimized to go just as fast as the C++ one? Probably, but then it will loose what makes Haskell the math language. With Haskell we get all the expressivity, but we pay the price of not being able to understand or easily tweak the runtime behavior. Just as a hint, Agda is even worse!
  10. The low-level represents ability to speak to the machine in the language most natural to it. High-level indicates ability to speak to the programmer succinctly and abstractly (math). In other words, the higher level languages relate more closely to the essence of the problem.
  11. We don’t want to use Haskell basically because we don’t want to be limited by its syntax.
  12. Discuss getopt and boost’s program options libraries. What if I want to use single rather than double dash? What if I want positional arguments to effect what comes after? What is it that I really want? If wanting these options requires yet another feature and complexity be added to the library, that is a good indicator that the semantic domain wasn’t nailed in the first place. Time to start over.
  13. Discuss getopt and boost’s program options libraries. What if I want to use single rather than double dash? What if I want positional arguments to effect what comes after? What is it that I really want? If wanting these options requires yet another feature and complexity be added to the library, that is a good indicator that the semantic domain wasn’t nailed in the first place. Time to start over.
  14. Flexible, composable, safe.
  15. Denotational semantics, but reversed of how they intended it. We go from the high-level math to the low-level implementation.