SlideShare a Scribd company logo
Generic Programming Galore Using D

                             Andrei Alexandrescu, PhD

                                 Research Scientist
                                     Facebook




c 2011 Andrei Alexandrescu                              1 / 33
37% off




c 2011 Andrei Alexandrescu   2 / 33
Generic Programming




c 2011 Andrei Alexandrescu                         3 / 33
What is Generic Programming?




c 2011 Andrei Alexandrescu      4 / 33
What is Generic Programming?


         • Find most general algorithm representation
             ◦ Narrowest requirements
             ◦ Widest guarantees
             ◦ Big-O() encapsulation should be a crime
             ◦ No need to regress to hand-written code




c 2011 Andrei Alexandrescu                               4 / 33
What is Generic Programming?


         • Find most general algorithm representation
             ◦ Narrowest requirements
             ◦ Widest guarantees
             ◦ Big-O() encapsulation should be a crime
             ◦ No need to regress to hand-written code
         • Define types to implement said requirements




c 2011 Andrei Alexandrescu                               4 / 33
What is Generic Programming?


         • Find most general algorithm representation
             ◦ Narrowest requirements
             ◦ Widest guarantees
             ◦ Big-O() encapsulation should be a crime
             ◦ No need to regress to hand-written code
         • Define types to implement said requirements
         • Leverage the algorithm for ultimate reuse




c 2011 Andrei Alexandrescu                               4 / 33
What is Generic Programming?


         • Find most general algorithm representation
             ◦ Narrowest requirements
             ◦ Widest guarantees
             ◦ Big-O() encapsulation should be a crime
             ◦ No need to regress to hand-written code
         • Define types to implement said requirements
         • Leverage the algorithm for ultimate reuse
         • ...
         • Profit!




c 2011 Andrei Alexandrescu                               4 / 33
What is Generic Programming?


         • Find most general algorithm representation
             ◦ Narrowest requirements
             ◦ Widest guarantees
             ◦ Big-O() encapsulation should be a crime
             ◦ No need to regress to hand-written code
         • Define types to implement said requirements
         • Leverage the algorithm for ultimate reuse
         • ...
         • Profit!

                                                         ´
         • Arguably one of the noblest endeavors of our metier


c 2011 Andrei Alexandrescu                                       4 / 33
Generic Programming


         • “Write once, instantiate anywhere”
             ◦ Specialized implementations welcome
         • Prefers static type information and static expansion
           (macro style)
         • Fosters strong mathematical underpinnings
             ◦ Minimizing assumptions common theme in math
         • Tenuous relationship with binary interfaces
         • Starts with algorithms, not interfaces or objects
         • “Premature encapsulation is the root of some
           derangement”



c 2011 Andrei Alexandrescu                                        5 / 33
Warmup: the “dream min”




         • Should work at efficiency comparable to hand-written
           code
         • Take variadic arguments: min(a, b, ...)
             ◦ Avoid nonsensical calls min() and min(a)
         • Work for all ordered types and conversions
         • Decline incompatible types, without prejudice




c 2011 Andrei Alexandrescu                                       6 / 33
First prototype




       auto min(L, R)(L lhs, R rhs) {
          return rhs < lhs ? rhs : lhs;
       }
       auto a = min(x, y);
         • This function is as efficient as any specialized,
           handwritten version (true genericity)
         • Deduction for argument types and result type




c 2011 Andrei Alexandrescu                                    7 / 33
Variadic arguments


       auto min(T...)(T x) {
         static if (x.length > 2)
           return min(min(x[0], x[1]), x[2 .. $]);
         else
           return x[0] > x[1] ? x[1] : x[0];
       }
       ...
       auto m = min(a + b, 100, c);
         • x is not an array
         • This is not classic recursion


c 2011 Andrei Alexandrescu                           8 / 33
Reject nonsensical calls



       auto min(T...)(T x) if (x.length > 1) {
         ...
       }
         • Rejects calls with 0 or 1 arguments
         • Allows other overloads to take over, e.g. min element
           over a collection
         • More work needed
             ◦ Only accept types with a valid intersection
             ◦ Only accept types comparable with ”<”



c 2011 Andrei Alexandrescu                                         9 / 33
Common type

         • Task: Given a list of types, find the common type of all
       template CommonType(T...)
       {
         static if (T.length == 1)
           alias T[0] CommonType;
         else
           static if (is(typeof(1 ? T[0].init : T[1].init) U))
              alias CommonType!(U, T[2 .. $]) CommonType;
         else
           alias void CommonType;
       }
       // Usage
       static assert(is(CommonType!(int, short, long) == long));


c 2011 Andrei Alexandrescu                                           10 / 33
Using CommonType



       auto min(T...)(T x)
       if (x.length > 1
         && is(typeof(CommonType!T.init < CommonType!T.init)
               == bool))
       {
         static if (x.length > 2)
           return min(min(x[0], x[1]), x[2 .. $]);
         else
           return x[0] > x[1] ? x[1] : x[0];
       }




c 2011 Andrei Alexandrescu                                 11 / 33
How about min over many elements?


       auto min(R)(R range)
       if (isInputRange!R &&
           is(typeof(range.front < range.front) == bool))
       {
         auto result = range.front;
         range.popFront();
         foreach (e; range) {
           if (e < result) result = e;
         }
         return result;
       }
       auto m = [ 1, 5, 2, 0, 7, 9 ].min();
         • Works over anything that can be iterated

c 2011 Andrei Alexandrescu                                  12 / 33
How about argmin now?

       auto argmin(alias fun, R)(R r)
       if (isInputRange!R &&
           is(typeof(fun(r.front) < fun(r.front)) == bool))
       {
         auto result = r.front;
         auto cache = fun(result);
         r.popFront();
         foreach (e; r) {
           auto cand = fun(e);
           if (cand > cache) continue;
           result = e;
           cache = cand;
         }
         return result;
       }

c 2011 Andrei Alexandrescu                                    13 / 33
argmin




       auto s = ["abc", "a", "xz"];
       auto m = s.argmin!((x) => x.length);
         • Works on anything iterable and any predicate
         • Predicate is passed by alias
         • No loss of efficiency




c 2011 Andrei Alexandrescu                                14 / 33
The Generative Connection




c 2011 Andrei Alexandrescu                           15 / 33
Generative programming




         • In brief: code that generates code
         • Generic programming often requires algorithm
           specialization
         • Specification often present in a DSL




c 2011 Andrei Alexandrescu                                16 / 33
Embedded DSLs




              Force into host language’s syntax?




c 2011 Andrei Alexandrescu                         17 / 33
Embedded DSLs



         •   Formatted printing?




c 2011 Andrei Alexandrescu         18 / 33
Embedded DSLs



         • Formatted printing?
         • Regular expressions?




c 2011 Andrei Alexandrescu        18 / 33
Embedded DSLs



         • Formatted printing?
         • Regular expressions?
         • EBNF?




c 2011 Andrei Alexandrescu        18 / 33
Embedded DSLs



         • Formatted printing?
         • Regular expressions?
         • EBNF?
         • PEG?




c 2011 Andrei Alexandrescu        18 / 33
Embedded DSLs



         •   Formatted printing?
         •   Regular expressions?
         •   EBNF?
         •   PEG?
         •   SQL?




c 2011 Andrei Alexandrescu          18 / 33
Embedded DSLs



         •   Formatted printing?
         •   Regular expressions?
         •   EBNF?
         •   PEG?
         •   SQL?


         •   . . . Pasta for everyone!


c 2011 Andrei Alexandrescu               18 / 33
Embedded DSLs



                    Here: use with native grammar


                             Process during compilation


                     Generate D code accordingly


c 2011 Andrei Alexandrescu                                19 / 33
Compile-Time Evaluation


         • A large subset of D available for compile-time evaluation
                 ulong factorial(uint n) {
                     ulong result = 1;
                     foreach (i; 2 .. n) result *= i;
                     return result;
                 }
                 ...
                 auto f1 = factorial(10); // run-time
                 static f2 = factorial(10); // compile-time



c 2011 Andrei Alexandrescu                                             20 / 33
Code injection with mixin



       mixin("writeln("hello, world");");
       mixin(generateSomeCode());
         • Not as glamorous as AST manipulation but darn
           effective
         • Easy to understand and debug



         • Now we have compile-time evaluation AND mixin. . .




c 2011 Andrei Alexandrescu                                      21 / 33
Wait a minute!



c 2011 Andrei Alexandrescu                    22 / 33
Example: bitfields in library


       struct A {
         int a;
         mixin(bitfields!(
           uint, "x",    2,
           int, "y",     3,
           uint, "z",    2,
           bool, "flag", 1));
       }
       A obj;
       obj.x = 2;
       obj.z = obj.x;

c 2011 Andrei Alexandrescu      23 / 33
Parser

       import pegged.grammar; // by Philippe Sigaud
       mixin(grammar("
         Expr     <    Factor AddExpr*
         AddExpr <     (’+’/’-’) Factor
         Factor   <    Primary MulExpr*
         MulExpr <     (’*’/’/’) Primary
         Primary <     Parens / Number / Variable
                       / ’-’ Primary
         Parens   <    ’(’ Expr ’)’
         Number   <~ [0-9]+
         Variable <- Identifier
       "));

c 2011 Andrei Alexandrescu                        24 / 33
Usage




       // Parsing at compile-time:
       static parseTree1 = Expr.parse(
         "1 + 2 - (3*x-5)*6");
       pragma(msg, parseTree1.capture);
       // Parsing at run-time:
       auto parseTree2 = Expr.parse(readln());
       writeln(parseTree2.capture);




c 2011 Andrei Alexandrescu                       25 / 33
Scaling up




       1000 lines of D grammar →
          3000 lines D parser



c 2011 Andrei Alexandrescu         26 / 33
Highly integrated lex+yacc



c 2011 Andrei Alexandrescu           27 / 33
What about regexen?



c 2011 Andrei Alexandrescu              28 / 33
Compile-time regular expressions



         • GSoC project by Dmitry Olshansky: FReD
         • Fully UTF capable, no special casing for ASCII
         • Two modes sharing the same backend:
                 auto r1 = regex("^.*/([^/]+)/?$");
                 static r2 = ctRegex!("^.*/([^/]+)/?$");
         • Run-time version uses intrinsics in a few places
         • Static version generates specialized automaton, then
           compiles it




c 2011 Andrei Alexandrescu                                        29 / 33
Summary




c 2011 Andrei Alexandrescu             31 / 33
Summary




         • Generic/generative programming—long unattained
           promise
         • D’s angle
             ◦ Powerful base language
             ◦ Type manipulation
             ◦ Compile-time evaluation
             ◦ Code generation




c 2011 Andrei Alexandrescu                                  32 / 33
Grill the Speaker!



   More about ranges? • Thought the talk was
   boring • Intriguing! • He lost me at mixin •
   Awesome • Went over my head • Meh • I wonder
   how I can implement binary search • What’s for
   dinner? • Accent is bothersome • Real
   programmers use C • Must. . . control. . . fist. . .
   of. . . death. . .



c 2011 Andrei Alexandrescu                               33 / 33

More Related Content

What's hot

Symbolic Execution And KLEE
Symbolic Execution And KLEESymbolic Execution And KLEE
Symbolic Execution And KLEE
Shauvik Roy Choudhary, Ph.D.
 
C language
C languageC language
C language
Robo India
 
Introduction to HDLs
Introduction to HDLsIntroduction to HDLs
Introduction to HDLs
IndiraPriyadarshini30
 
Dynamic Type Inference for Gradual Hindley–Milner Typing
Dynamic Type Inference for Gradual Hindley–Milner TypingDynamic Type Inference for Gradual Hindley–Milner Typing
Dynamic Type Inference for Gradual Hindley–Milner Typing
Yusuke Miyazaki
 
Temporal logic and functional reactive programming
Temporal logic and functional reactive programmingTemporal logic and functional reactive programming
Temporal logic and functional reactive programming
Sergei Winitzki
 
Being Expressive in Code
Being Expressive in CodeBeing Expressive in Code
Being Expressive in Code
Eamonn Boyle
 
EdSketch: Execution-Driven Sketching for Java
EdSketch: Execution-Driven Sketching for JavaEdSketch: Execution-Driven Sketching for Java
EdSketch: Execution-Driven Sketching for Java
Lisa Hua
 
what engineers don't know (but probably mathematicians do)
what engineers don't know (but probably mathematicians do)what engineers don't know (but probably mathematicians do)
what engineers don't know (but probably mathematicians do)
budi rahardjo
 

What's hot (8)

Symbolic Execution And KLEE
Symbolic Execution And KLEESymbolic Execution And KLEE
Symbolic Execution And KLEE
 
C language
C languageC language
C language
 
Introduction to HDLs
Introduction to HDLsIntroduction to HDLs
Introduction to HDLs
 
Dynamic Type Inference for Gradual Hindley–Milner Typing
Dynamic Type Inference for Gradual Hindley–Milner TypingDynamic Type Inference for Gradual Hindley–Milner Typing
Dynamic Type Inference for Gradual Hindley–Milner Typing
 
Temporal logic and functional reactive programming
Temporal logic and functional reactive programmingTemporal logic and functional reactive programming
Temporal logic and functional reactive programming
 
Being Expressive in Code
Being Expressive in CodeBeing Expressive in Code
Being Expressive in Code
 
EdSketch: Execution-Driven Sketching for Java
EdSketch: Execution-Driven Sketching for JavaEdSketch: Execution-Driven Sketching for Java
EdSketch: Execution-Driven Sketching for Java
 
what engineers don't know (but probably mathematicians do)
what engineers don't know (but probably mathematicians do)what engineers don't know (but probably mathematicians do)
what engineers don't know (but probably mathematicians do)
 

Similar to Generic Programming Galore Using D

Logic Programming and ILP
Logic Programming and ILPLogic Programming and ILP
Logic Programming and ILP
Pierre de Lacaze
 
Interm codegen
Interm codegenInterm codegen
Interm codegen
Anshul Sharma
 
iterators-must-go
iterators-must-goiterators-must-go
iterators-must-go
Hiroshi Ono
 
(chapter 1) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 1) A Concise and Practical Introduction to Programming Algorithms in...(chapter 1) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 1) A Concise and Practical Introduction to Programming Algorithms in...
Frank Nielsen
 
Contest Tips and Tricks
Contest Tips and TricksContest Tips and Tricks
Contest Tips and Tricks
mbuzdalov
 
Introduction to Elixir
Introduction to ElixirIntroduction to Elixir
Introduction to Elixir
brien_wankel
 
Global DSL workshop slides
Global DSL workshop slidesGlobal DSL workshop slides
Global DSL workshop slides
ericupnorth
 
1 cc
1 cc1 cc
1 cc
Jay Soni
 
IN4308 1
IN4308 1IN4308 1
IN4308 1
Eelco Visser
 
On being a professional software developer
On being a professional software developerOn being a professional software developer
On being a professional software developer
Anton Kirillov
 
Crystal internals (part 1)
Crystal internals (part 1)Crystal internals (part 1)
Crystal internals (part 1)
Ary Borenszweig
 
Crystal internals (part 1)
Crystal internals (part 1)Crystal internals (part 1)
Crystal internals (part 1)
Ary Borenszweig
 
Crystal internals (part 1)
Crystal internals (part 1)Crystal internals (part 1)
Crystal internals (part 1)
Crystal Language
 
A Replay Approach to Software Validation
A Replay Approach to Software ValidationA Replay Approach to Software Validation
A Replay Approach to Software Validation
James Pascoe
 
Skiron - Experiments in CPU Design in D
Skiron - Experiments in CPU Design in DSkiron - Experiments in CPU Design in D
Skiron - Experiments in CPU Design in D
Mithun Hunsur
 
Clojure intro
Clojure introClojure intro
Clojure intro
Basav Nagur
 
Introduction to Prolog
Introduction to PrologIntroduction to Prolog
Introduction to Prolog
Chamath Sajeewa
 
Антон Кириллов, ZeptoLab
Антон Кириллов, ZeptoLabАнтон Кириллов, ZeptoLab
Антон Кириллов, ZeptoLab
Diana Dymolazova
 
Parallel Optimization in Machine Learning
Parallel Optimization in Machine LearningParallel Optimization in Machine Learning
Parallel Optimization in Machine Learning
Fabian Pedregosa
 
Introduction to Elixir
Introduction to ElixirIntroduction to Elixir
Introduction to Elixir
Diacode
 

Similar to Generic Programming Galore Using D (20)

Logic Programming and ILP
Logic Programming and ILPLogic Programming and ILP
Logic Programming and ILP
 
Interm codegen
Interm codegenInterm codegen
Interm codegen
 
iterators-must-go
iterators-must-goiterators-must-go
iterators-must-go
 
(chapter 1) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 1) A Concise and Practical Introduction to Programming Algorithms in...(chapter 1) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 1) A Concise and Practical Introduction to Programming Algorithms in...
 
Contest Tips and Tricks
Contest Tips and TricksContest Tips and Tricks
Contest Tips and Tricks
 
Introduction to Elixir
Introduction to ElixirIntroduction to Elixir
Introduction to Elixir
 
Global DSL workshop slides
Global DSL workshop slidesGlobal DSL workshop slides
Global DSL workshop slides
 
1 cc
1 cc1 cc
1 cc
 
IN4308 1
IN4308 1IN4308 1
IN4308 1
 
On being a professional software developer
On being a professional software developerOn being a professional software developer
On being a professional software developer
 
Crystal internals (part 1)
Crystal internals (part 1)Crystal internals (part 1)
Crystal internals (part 1)
 
Crystal internals (part 1)
Crystal internals (part 1)Crystal internals (part 1)
Crystal internals (part 1)
 
Crystal internals (part 1)
Crystal internals (part 1)Crystal internals (part 1)
Crystal internals (part 1)
 
A Replay Approach to Software Validation
A Replay Approach to Software ValidationA Replay Approach to Software Validation
A Replay Approach to Software Validation
 
Skiron - Experiments in CPU Design in D
Skiron - Experiments in CPU Design in DSkiron - Experiments in CPU Design in D
Skiron - Experiments in CPU Design in D
 
Clojure intro
Clojure introClojure intro
Clojure intro
 
Introduction to Prolog
Introduction to PrologIntroduction to Prolog
Introduction to Prolog
 
Антон Кириллов, ZeptoLab
Антон Кириллов, ZeptoLabАнтон Кириллов, ZeptoLab
Антон Кириллов, ZeptoLab
 
Parallel Optimization in Machine Learning
Parallel Optimization in Machine LearningParallel Optimization in Machine Learning
Parallel Optimization in Machine Learning
 
Introduction to Elixir
Introduction to ElixirIntroduction to Elixir
Introduction to Elixir
 

Recently uploaded

Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
Tatiana Kojar
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
Alex Pruden
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Neo4j
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
Fwdays
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
Edge AI and Vision Alliance
 
Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
Ivo Velitchkov
 
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectorsConnector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
DianaGray10
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 
The Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptxThe Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptx
operationspcvita
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
Public CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptxPublic CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptx
marufrahmanstratejm
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
DanBrown980551
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
Leveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and StandardsLeveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and Standards
Neo4j
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
Data Hops
 

Recently uploaded (20)

Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
 
Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
 
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectorsConnector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 
The Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptxThe Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptx
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
Public CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptxPublic CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptx
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
Leveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and StandardsLeveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and Standards
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
 

Generic Programming Galore Using D

  • 1. Generic Programming Galore Using D Andrei Alexandrescu, PhD Research Scientist Facebook c 2011 Andrei Alexandrescu 1 / 33
  • 2. 37% off c 2011 Andrei Alexandrescu 2 / 33
  • 3. Generic Programming c 2011 Andrei Alexandrescu 3 / 33
  • 4. What is Generic Programming? c 2011 Andrei Alexandrescu 4 / 33
  • 5. What is Generic Programming? • Find most general algorithm representation ◦ Narrowest requirements ◦ Widest guarantees ◦ Big-O() encapsulation should be a crime ◦ No need to regress to hand-written code c 2011 Andrei Alexandrescu 4 / 33
  • 6. What is Generic Programming? • Find most general algorithm representation ◦ Narrowest requirements ◦ Widest guarantees ◦ Big-O() encapsulation should be a crime ◦ No need to regress to hand-written code • Define types to implement said requirements c 2011 Andrei Alexandrescu 4 / 33
  • 7. What is Generic Programming? • Find most general algorithm representation ◦ Narrowest requirements ◦ Widest guarantees ◦ Big-O() encapsulation should be a crime ◦ No need to regress to hand-written code • Define types to implement said requirements • Leverage the algorithm for ultimate reuse c 2011 Andrei Alexandrescu 4 / 33
  • 8. What is Generic Programming? • Find most general algorithm representation ◦ Narrowest requirements ◦ Widest guarantees ◦ Big-O() encapsulation should be a crime ◦ No need to regress to hand-written code • Define types to implement said requirements • Leverage the algorithm for ultimate reuse • ... • Profit! c 2011 Andrei Alexandrescu 4 / 33
  • 9. What is Generic Programming? • Find most general algorithm representation ◦ Narrowest requirements ◦ Widest guarantees ◦ Big-O() encapsulation should be a crime ◦ No need to regress to hand-written code • Define types to implement said requirements • Leverage the algorithm for ultimate reuse • ... • Profit! ´ • Arguably one of the noblest endeavors of our metier c 2011 Andrei Alexandrescu 4 / 33
  • 10. Generic Programming • “Write once, instantiate anywhere” ◦ Specialized implementations welcome • Prefers static type information and static expansion (macro style) • Fosters strong mathematical underpinnings ◦ Minimizing assumptions common theme in math • Tenuous relationship with binary interfaces • Starts with algorithms, not interfaces or objects • “Premature encapsulation is the root of some derangement” c 2011 Andrei Alexandrescu 5 / 33
  • 11. Warmup: the “dream min” • Should work at efficiency comparable to hand-written code • Take variadic arguments: min(a, b, ...) ◦ Avoid nonsensical calls min() and min(a) • Work for all ordered types and conversions • Decline incompatible types, without prejudice c 2011 Andrei Alexandrescu 6 / 33
  • 12. First prototype auto min(L, R)(L lhs, R rhs) { return rhs < lhs ? rhs : lhs; } auto a = min(x, y); • This function is as efficient as any specialized, handwritten version (true genericity) • Deduction for argument types and result type c 2011 Andrei Alexandrescu 7 / 33
  • 13. Variadic arguments auto min(T...)(T x) { static if (x.length > 2) return min(min(x[0], x[1]), x[2 .. $]); else return x[0] > x[1] ? x[1] : x[0]; } ... auto m = min(a + b, 100, c); • x is not an array • This is not classic recursion c 2011 Andrei Alexandrescu 8 / 33
  • 14. Reject nonsensical calls auto min(T...)(T x) if (x.length > 1) { ... } • Rejects calls with 0 or 1 arguments • Allows other overloads to take over, e.g. min element over a collection • More work needed ◦ Only accept types with a valid intersection ◦ Only accept types comparable with ”<” c 2011 Andrei Alexandrescu 9 / 33
  • 15. Common type • Task: Given a list of types, find the common type of all template CommonType(T...) { static if (T.length == 1) alias T[0] CommonType; else static if (is(typeof(1 ? T[0].init : T[1].init) U)) alias CommonType!(U, T[2 .. $]) CommonType; else alias void CommonType; } // Usage static assert(is(CommonType!(int, short, long) == long)); c 2011 Andrei Alexandrescu 10 / 33
  • 16. Using CommonType auto min(T...)(T x) if (x.length > 1 && is(typeof(CommonType!T.init < CommonType!T.init) == bool)) { static if (x.length > 2) return min(min(x[0], x[1]), x[2 .. $]); else return x[0] > x[1] ? x[1] : x[0]; } c 2011 Andrei Alexandrescu 11 / 33
  • 17. How about min over many elements? auto min(R)(R range) if (isInputRange!R && is(typeof(range.front < range.front) == bool)) { auto result = range.front; range.popFront(); foreach (e; range) { if (e < result) result = e; } return result; } auto m = [ 1, 5, 2, 0, 7, 9 ].min(); • Works over anything that can be iterated c 2011 Andrei Alexandrescu 12 / 33
  • 18. How about argmin now? auto argmin(alias fun, R)(R r) if (isInputRange!R && is(typeof(fun(r.front) < fun(r.front)) == bool)) { auto result = r.front; auto cache = fun(result); r.popFront(); foreach (e; r) { auto cand = fun(e); if (cand > cache) continue; result = e; cache = cand; } return result; } c 2011 Andrei Alexandrescu 13 / 33
  • 19. argmin auto s = ["abc", "a", "xz"]; auto m = s.argmin!((x) => x.length); • Works on anything iterable and any predicate • Predicate is passed by alias • No loss of efficiency c 2011 Andrei Alexandrescu 14 / 33
  • 20. The Generative Connection c 2011 Andrei Alexandrescu 15 / 33
  • 21. Generative programming • In brief: code that generates code • Generic programming often requires algorithm specialization • Specification often present in a DSL c 2011 Andrei Alexandrescu 16 / 33
  • 22. Embedded DSLs Force into host language’s syntax? c 2011 Andrei Alexandrescu 17 / 33
  • 23. Embedded DSLs • Formatted printing? c 2011 Andrei Alexandrescu 18 / 33
  • 24. Embedded DSLs • Formatted printing? • Regular expressions? c 2011 Andrei Alexandrescu 18 / 33
  • 25. Embedded DSLs • Formatted printing? • Regular expressions? • EBNF? c 2011 Andrei Alexandrescu 18 / 33
  • 26. Embedded DSLs • Formatted printing? • Regular expressions? • EBNF? • PEG? c 2011 Andrei Alexandrescu 18 / 33
  • 27. Embedded DSLs • Formatted printing? • Regular expressions? • EBNF? • PEG? • SQL? c 2011 Andrei Alexandrescu 18 / 33
  • 28. Embedded DSLs • Formatted printing? • Regular expressions? • EBNF? • PEG? • SQL? • . . . Pasta for everyone! c 2011 Andrei Alexandrescu 18 / 33
  • 29. Embedded DSLs Here: use with native grammar Process during compilation Generate D code accordingly c 2011 Andrei Alexandrescu 19 / 33
  • 30. Compile-Time Evaluation • A large subset of D available for compile-time evaluation ulong factorial(uint n) { ulong result = 1; foreach (i; 2 .. n) result *= i; return result; } ... auto f1 = factorial(10); // run-time static f2 = factorial(10); // compile-time c 2011 Andrei Alexandrescu 20 / 33
  • 31. Code injection with mixin mixin("writeln("hello, world");"); mixin(generateSomeCode()); • Not as glamorous as AST manipulation but darn effective • Easy to understand and debug • Now we have compile-time evaluation AND mixin. . . c 2011 Andrei Alexandrescu 21 / 33
  • 32. Wait a minute! c 2011 Andrei Alexandrescu 22 / 33
  • 33. Example: bitfields in library struct A { int a; mixin(bitfields!( uint, "x", 2, int, "y", 3, uint, "z", 2, bool, "flag", 1)); } A obj; obj.x = 2; obj.z = obj.x; c 2011 Andrei Alexandrescu 23 / 33
  • 34. Parser import pegged.grammar; // by Philippe Sigaud mixin(grammar(" Expr < Factor AddExpr* AddExpr < (’+’/’-’) Factor Factor < Primary MulExpr* MulExpr < (’*’/’/’) Primary Primary < Parens / Number / Variable / ’-’ Primary Parens < ’(’ Expr ’)’ Number <~ [0-9]+ Variable <- Identifier ")); c 2011 Andrei Alexandrescu 24 / 33
  • 35. Usage // Parsing at compile-time: static parseTree1 = Expr.parse( "1 + 2 - (3*x-5)*6"); pragma(msg, parseTree1.capture); // Parsing at run-time: auto parseTree2 = Expr.parse(readln()); writeln(parseTree2.capture); c 2011 Andrei Alexandrescu 25 / 33
  • 36. Scaling up 1000 lines of D grammar → 3000 lines D parser c 2011 Andrei Alexandrescu 26 / 33
  • 37. Highly integrated lex+yacc c 2011 Andrei Alexandrescu 27 / 33
  • 38. What about regexen? c 2011 Andrei Alexandrescu 28 / 33
  • 39. Compile-time regular expressions • GSoC project by Dmitry Olshansky: FReD • Fully UTF capable, no special casing for ASCII • Two modes sharing the same backend: auto r1 = regex("^.*/([^/]+)/?$"); static r2 = ctRegex!("^.*/([^/]+)/?$"); • Run-time version uses intrinsics in a few places • Static version generates specialized automaton, then compiles it c 2011 Andrei Alexandrescu 29 / 33
  • 40.
  • 41. Summary c 2011 Andrei Alexandrescu 31 / 33
  • 42. Summary • Generic/generative programming—long unattained promise • D’s angle ◦ Powerful base language ◦ Type manipulation ◦ Compile-time evaluation ◦ Code generation c 2011 Andrei Alexandrescu 32 / 33
  • 43. Grill the Speaker! More about ranges? • Thought the talk was boring • Intriguing! • He lost me at mixin • Awesome • Went over my head • Meh • I wonder how I can implement binary search • What’s for dinner? • Accent is bothersome • Real programmers use C • Must. . . control. . . fist. . . of. . . death. . . c 2011 Andrei Alexandrescu 33 / 33