SlideShare ist ein Scribd-Unternehmen logo
1 von 33
Downloaden Sie, um offline zu lesen
Perl and Haskell: Can the Twain Ever Meet?
Wim Vanderbauwhede
School of Computing Science, University of Glasgow, UK
(tl;dr: yes)
Outline
Perl
Haskell
Calling Haskell from Perl
C
Haskell FFI
Perl Inline::C
Serialisation
What About the Types?
The Final Picture
The Need for Proper Typing
A Modest Proposal
Implementation
Internals
Example
Conclusions
Perl ...
Notorious
$_=’while(read+STDIN,$_,2048){$a=29;$b=73;
$c=142;$t=255;@t=map{$_%16or$t^=$c^=($m=
(11,10,116,100,11,122,20,100)[$_/16%8])&110;
$t^=(72,@z=(64,72,$a^=12*($_%16 -2?0:$m&17)),
$b^=$_%64?12:0,@z)[$_%8]}(16..271);
if((@a=unx"C*",$_)[20]&48){$h =5;$_=unxb24,
join"",@b=map{xB8,unxb8,chr($_^$a[--$h+84])}
@ARGV;s/...$/1$&/;$ d=unxV,xb25,$_;$e=256|
(ord$b[4])<‌<9|ord$b[3];$d=$d>‌>8^($f=$t&
($d>‌>12^$d>‌>4^$d^$d/8))<‌<17,$e=$e>‌>8^($t
&($g=($q=$e>‌>14&7^$e)^$q*8^$q<‌<6))<‌<9,$_=
$t[$_]^(($h>‌>=8)+=$f+(~$g&$t))for
@a[128..$#a]}print+x"C*",@a}’;s/x/pack+/g;
eval;
But I like Perl
Haskell ...
Most empathically not
dynamically typed ...
Makes easy things hard ...
But I like Haskell
Haskell ...
a reputation of being esoteric
Monas Hieroglyphica,
(“The Hieroglyphic Monad”),
John Dee, Antwerp 1564
Calling Haskell from Perl
Why?
Calling Haskell from Perl
Should be as simple as:
Calling Haskell from Perl
C, the lingua franca
Haskell FFI to call Haskell from C
Perl Inline::C to call C from Perl
Serialisation
Code Generation
The call to “use Call::Haskell” triggers extensive code generation:
Haskell FFI and serialisation wrappers
Corresponding C wrappers and create a C library
Inline::C wrapper to call the functions in the C library
Perl serialisation wrapper
Compile only when Haskell source code has changed, otherwise
cache
Serialisation
JSON? YAML? MessagePack? No: Read and Show
Because serialisation needs to be type-aware
Serialisation of Perl values is done via a custom showH function
uses Haskell type information via Data.Typeable, serialised using
show, converted to a Perl datastructure in Haskell and deserialised
using eval.
De-serialisation of Perl serialised values in Haskell is done via
read
Serialisation of Haskell values is done via show
string generated by show is converted into Perl code in Haskell
De-serialisation of Haskell result is done via a custom readH
function
uses eval and Perl’s autload feature
Linking
FFI uses ghc as linker
Perl requires gcc linker
ghc does not compile dynamic libraries by default
Lots of fun
The Final Picture
1. Perl script calls a
2. Perl serialisation wrapper which calls a
3. Perl Inline::C wrapper which calls a
4. C FFI wrapper which calls a
5. Haskell FFI wrapper which calls a
6. Haskell serialisation wrapper which calls
7. the original Haskell function
All wrappers are generated and built automatically on loading
Call::Haskell
What About the Types?
The outlined approach relies on Data.Typeable, Read and Show.
Data.Typeable does not provide information on type constructors
for algebraic types.
So this approach only works for “primitive” types and containers
holding primitive types.
This is already quite a lot, but it’s not good enough.
We could add other types (e.g. Data.Map and Maybe) ad hoc
However ...
The Need for Proper Typing
There is a fundamental issue with variant types.
Given following Haskell type:
data Qual a = Groot a | Klein a
It is impossible to generate the correctly typed value for Haskell
unless the value in Perl is also typed with the same information!
So we need a type system for Perl...
A Modest Proposal
I propose to create a type system to type datastructures and
function signatures in a dynamically typed language (Perl),
without changing anything to the language itself
but nevertheless with an acceptable and usable syntax.
The types must be compatible with Haskell’s types so that it is
possible to call Haskell functions with well-typed arguments and
return values.
show and read the typed values in Haskell fashion.
Basic Functionality
Declare the type of a typed variable:
tv :: T
Construct a typed value from other typed and/or untyped values:
tv = TC v
Bind a typed value to a typed variable:
tv = tv
Convert a typed value into an untyped value:
v
u
= tv
A Simple Type System
The type system provides:
The primitive scalar types Int, Float, String, Bool.
type TI = Int
type TF = Float
The container types Tuple, Array and Map:
type TT = (T1, T2, ..., TN )
type TA = [T1]
type TM = {Tk , Tv }
A mechanism to declare and construct sum and product types:
data TS = T1 | T2 ... TN
data TP = TCP T1 ... TN
Implementation
To implement this type system in Perl, we use
functions for the type constructors,
a small API of type naming, binding and construction functions.
prototypes to construct the actual types. Prototypes are functions
that return a type descriptor.
lightweight objects to represent the typed values and the type
descriptors returned by the prototypes.
The implementation relies on two language features:
a function can query the name of its callers (caller in Perl)
data structures can be transformed into lightweight objects (bless
in Perl)
newtype and typename
To create type constructors:
TC = newtype T (Prototype T1...TN )
If the type T is polymorphic, the type name can take parameters:
TC = newtype (T a b) (Prototype a b)
Also used for container types
TC = newtype T (Prototype T1...TN )
And to create an alias for an existing primitive type
T = newtype Tprim
To declare the type name T
T = typename
Prototypes
Algebraic datatypes:
Record: For product types, with optional support for named fields
Variant: For sum types
Container types:
Tuple: For tuples
Array: For lists
Map: For dictionaries
Functions: Function
To construct primitive types: Scalar
type and bind
To declare a typed variable
type tv T
If the type is a polymorphic type, we can provide the type
argument:
type tv (T T1)
To bind a typed variable to a value, we use bind, which
corresponds to “=” in Haskell.
bind tv tv
If the type of a typed variable is primitive, bind can take an
untyped value as the argument:
bind tv v
untype, show and read
To return an untyped value from a typed value
v = untype tv
Finally, read and show work as in Haskell
Internals: Type Names and
Prototypes
Type Names
The typename function returns a tuple of the name of the type
and a list of the names parameters, if any. For example, given
Couldbe = typename
then the call Couldbe a b will return the tuple (Couldbe, [a,b]).
Prototypes
The prototypes take type name functions as arguments, and
return a type descriptor, implemented as a lightweight object.
Prototypes can only be called as argument to newtype, which in
its turn can only be called in the body of a type constructor
function. For example:
IntVar = typename
MkIntVar = newtype IntVar (Record String Int)
The call to Record will return and object of type Record with as
attributes the type constructor name and a list of arguments to
the constructor, i.e. typenames
Internals: Typed Value Objects and
Type Construction
Typed Value Object
An object with attributes Type and Value. The Type attribute
contains the information returned by the typename or prototype
calls, the Value attribute is populated by a call to newtype or bind.
Type Construction
The call to newtype typechecks the arguments against the type
information returned by the prototype, and returns a typed value
object, with the Type field provided by the prototype.
Internals: Typing and Binding
The call to type returns a typed value object with empty Value
attribute, to be filled by a call to bind.
The call to bind takes a value, typechecks it and stores it in the
Value attribute of the typed value.
If the type is a primitive type or a container type holding primitive
types, then the value can be untyped and is stored as-is in the
Value attribute. In that case, the only checking that is performed is
on the type of the container.
Otherwise, the value must be typed and will be typechecked.
Internals: Typing and Binding
For example:
type iv IntVar
bind iv (MkIntVar “55” 7188 )
The call to MkIntVar will return a typed value object with as Type
attribute a Record object with typename IntVar. The typed value
iv will contain as Type attribute a tuple with as first argument the
typename IntVar. Type checking is simply a comparison of the
typenames.
In a simpler example:
type iv’ Int
bind iv’ (Int 42)
the call to (Int 42) would return a typed value object, and the bind
call would typecheck the typename from the Type attribute with
the typename from iv’
Function Types
We often want to create typed functions from untyped functions.
type f Int -> Int -> Int
bind f (x y ->x+y)
But an untyped function can still take and return typed values:
type f (Int,Int) -> Maybe Int
bind f ((x,y) -> if (y/=0) then Just x/y else Nothing)
We allow both bare and typed values for the argument, and
return typed values from the function.
The call to bind creates a new function which takes typed
arguments, typechecks, untypes them if required, passes them
to the original function, and types the return value if required.
Polymorphic Binary Tree Example
Polymorphic Binary Tree
Tree = typename
Branch = newtype (Tree a) (Variant Tree a Tree)
Leaf = newtype (Tree a) Variant
type tree Tree(Int)
bind tree (Branch (Branch Leaf 41 Leaf) 42 Leaf)
Actual Perl code:
Typed Function Call Example
use Call::Haskell import => 'VarDeclParser( parse_vardecl )';
use Types;
use VarDecl;
my $tstr = String("integer :: v");
type my $fp = String => VarDecl;
bind $fp, &parse_vardecl;
my $tres = $fp−>($tstr);
say show $tres;
my $res = untype $tres;
Summary
Want proper typechecking in Perl?
https://github.com/wimvanderbauwhede/Perl-Functional-Types
Want to call Haskell from Perl?
https://github.com/wimvanderbauwhede/Perl-Call-Haskell
Thank you! Questions?

Weitere ähnliche Inhalte

Was ist angesagt?

Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheoryKnoldus Inc.
 
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...Philip Schwarz
 
Real World Haskell: Lecture 7
Real World Haskell: Lecture 7Real World Haskell: Lecture 7
Real World Haskell: Lecture 7Bryan O'Sullivan
 
Real World Haskell: Lecture 3
Real World Haskell: Lecture 3Real World Haskell: Lecture 3
Real World Haskell: Lecture 3Bryan O'Sullivan
 
Real World Haskell: Lecture 1
Real World Haskell: Lecture 1Real World Haskell: Lecture 1
Real World Haskell: Lecture 1Bryan O'Sullivan
 
3 kotlin vs. java- what kotlin has that java does not
3  kotlin vs. java- what kotlin has that java does not3  kotlin vs. java- what kotlin has that java does not
3 kotlin vs. java- what kotlin has that java does notSergey Bandysik
 
Big picture of category theory in scala with deep dive into contravariant and...
Big picture of category theory in scala with deep dive into contravariant and...Big picture of category theory in scala with deep dive into contravariant and...
Big picture of category theory in scala with deep dive into contravariant and...Piotr Paradziński
 
Function Applicative for Great Good of Palindrome Checker Function - Polyglot...
Function Applicative for Great Good of Palindrome Checker Function - Polyglot...Function Applicative for Great Good of Palindrome Checker Function - Polyglot...
Function Applicative for Great Good of Palindrome Checker Function - Polyglot...Philip Schwarz
 
Applicative Functor - Part 3
Applicative Functor - Part 3Applicative Functor - Part 3
Applicative Functor - Part 3Philip Schwarz
 
Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parametersKnoldus Inc.
 
Scala 3 enum for a terser Option Monad Algebraic Data Type
Scala 3 enum for a terser Option Monad Algebraic Data TypeScala 3 enum for a terser Option Monad Algebraic Data Type
Scala 3 enum for a terser Option Monad Algebraic Data TypePhilip Schwarz
 
Strinng Classes in c++
Strinng Classes in c++Strinng Classes in c++
Strinng Classes in c++Vikash Dhal
 
Introducing Assignment invalidates the Substitution Model of Evaluation and v...
Introducing Assignment invalidates the Substitution Model of Evaluation and v...Introducing Assignment invalidates the Substitution Model of Evaluation and v...
Introducing Assignment invalidates the Substitution Model of Evaluation and v...Philip Schwarz
 
Let's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APILet's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APIMario Fusco
 

Was ist angesagt? (20)

Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
 
Clojure basics
Clojure basicsClojure basics
Clojure basics
 
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
 
Real World Haskell: Lecture 7
Real World Haskell: Lecture 7Real World Haskell: Lecture 7
Real World Haskell: Lecture 7
 
Real World Haskell: Lecture 3
Real World Haskell: Lecture 3Real World Haskell: Lecture 3
Real World Haskell: Lecture 3
 
Monad Fact #4
Monad Fact #4Monad Fact #4
Monad Fact #4
 
Real World Haskell: Lecture 1
Real World Haskell: Lecture 1Real World Haskell: Lecture 1
Real World Haskell: Lecture 1
 
3 kotlin vs. java- what kotlin has that java does not
3  kotlin vs. java- what kotlin has that java does not3  kotlin vs. java- what kotlin has that java does not
3 kotlin vs. java- what kotlin has that java does not
 
The string class
The string classThe string class
The string class
 
Big picture of category theory in scala with deep dive into contravariant and...
Big picture of category theory in scala with deep dive into contravariant and...Big picture of category theory in scala with deep dive into contravariant and...
Big picture of category theory in scala with deep dive into contravariant and...
 
Function Applicative for Great Good of Palindrome Checker Function - Polyglot...
Function Applicative for Great Good of Palindrome Checker Function - Polyglot...Function Applicative for Great Good of Palindrome Checker Function - Polyglot...
Function Applicative for Great Good of Palindrome Checker Function - Polyglot...
 
Applicative Functor - Part 3
Applicative Functor - Part 3Applicative Functor - Part 3
Applicative Functor - Part 3
 
Bc0037
Bc0037Bc0037
Bc0037
 
Compile time polymorphism
Compile time polymorphismCompile time polymorphism
Compile time polymorphism
 
Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parameters
 
Scala 3 enum for a terser Option Monad Algebraic Data Type
Scala 3 enum for a terser Option Monad Algebraic Data TypeScala 3 enum for a terser Option Monad Algebraic Data Type
Scala 3 enum for a terser Option Monad Algebraic Data Type
 
Strinng Classes in c++
Strinng Classes in c++Strinng Classes in c++
Strinng Classes in c++
 
Introducing Assignment invalidates the Substitution Model of Evaluation and v...
Introducing Assignment invalidates the Substitution Model of Evaluation and v...Introducing Assignment invalidates the Substitution Model of Evaluation and v...
Introducing Assignment invalidates the Substitution Model of Evaluation and v...
 
Let's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APILet's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java API
 
C++ theory
C++ theoryC++ theory
C++ theory
 

Ähnlich wie Perl and Haskell: Can the Twain Ever Meet? (tl;dr: yes)

C# Summer course - Lecture 2
C# Summer course - Lecture 2C# Summer course - Lecture 2
C# Summer course - Lecture 2mohamedsamyali
 
All About ... Functions
All About ... FunctionsAll About ... Functions
All About ... FunctionsMichal Bigos
 
CS-XII Python Fundamentals.pdf
CS-XII Python Fundamentals.pdfCS-XII Python Fundamentals.pdf
CS-XII Python Fundamentals.pdfIda Lumintu
 
Back to the Future with TypeScript
Back to the Future with TypeScriptBack to the Future with TypeScript
Back to the Future with TypeScriptAleš Najmann
 
Types, classes and concepts
Types, classes and conceptsTypes, classes and concepts
Types, classes and conceptsNicola Bonelli
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesTomer Gabel
 
C Types - Extending Python
C Types - Extending PythonC Types - Extending Python
C Types - Extending PythonPriyank Kapadia
 
Core csharp and net quick reference
Core csharp and net quick referenceCore csharp and net quick reference
Core csharp and net quick referenceilesh raval
 
Core c sharp and .net quick reference
Core c sharp and .net quick referenceCore c sharp and .net quick reference
Core c sharp and .net quick referenceArduino Aficionado
 
Python variables and data types.pptx
Python variables and data types.pptxPython variables and data types.pptx
Python variables and data types.pptxAkshayAggarwal79
 
Solid C++ by Example
Solid C++ by ExampleSolid C++ by Example
Solid C++ by ExampleOlve Maudal
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScriptGarth Gilmour
 

Ähnlich wie Perl and Haskell: Can the Twain Ever Meet? (tl;dr: yes) (20)

C# Summer course - Lecture 2
C# Summer course - Lecture 2C# Summer course - Lecture 2
C# Summer course - Lecture 2
 
Savitch Ch 17
Savitch Ch 17Savitch Ch 17
Savitch Ch 17
 
unit 1.docx
unit 1.docxunit 1.docx
unit 1.docx
 
All About ... Functions
All About ... FunctionsAll About ... Functions
All About ... Functions
 
CS-XII Python Fundamentals.pdf
CS-XII Python Fundamentals.pdfCS-XII Python Fundamentals.pdf
CS-XII Python Fundamentals.pdf
 
DAY_1.3.pptx
DAY_1.3.pptxDAY_1.3.pptx
DAY_1.3.pptx
 
Savitch ch 17
Savitch ch 17Savitch ch 17
Savitch ch 17
 
Scala Paradigms
Scala ParadigmsScala Paradigms
Scala Paradigms
 
Back to the Future with TypeScript
Back to the Future with TypeScriptBack to the Future with TypeScript
Back to the Future with TypeScript
 
Chapter 6 Intermediate Code Generation
Chapter 6   Intermediate Code GenerationChapter 6   Intermediate Code Generation
Chapter 6 Intermediate Code Generation
 
Types, classes and concepts
Types, classes and conceptsTypes, classes and concepts
Types, classes and concepts
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 
C Types - Extending Python
C Types - Extending PythonC Types - Extending Python
C Types - Extending Python
 
Core csharp and net quick reference
Core csharp and net quick referenceCore csharp and net quick reference
Core csharp and net quick reference
 
Core c sharp and .net quick reference
Core c sharp and .net quick referenceCore c sharp and .net quick reference
Core c sharp and .net quick reference
 
Python variables and data types.pptx
Python variables and data types.pptxPython variables and data types.pptx
Python variables and data types.pptx
 
Solid C++ by Example
Solid C++ by ExampleSolid C++ by Example
Solid C++ by Example
 
Notes(1).pptx
Notes(1).pptxNotes(1).pptx
Notes(1).pptx
 
DATA TYPE IN PYTHON
DATA TYPE IN PYTHONDATA TYPE IN PYTHON
DATA TYPE IN PYTHON
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScript
 

Mehr von Wim Vanderbauwhede

Haku, a toy functional language based on literary Japanese
Haku, a toy functional language  based on literary JapaneseHaku, a toy functional language  based on literary Japanese
Haku, a toy functional language based on literary JapaneseWim Vanderbauwhede
 
A few thoughts on work life-balance
A few thoughts on work life-balanceA few thoughts on work life-balance
A few thoughts on work life-balanceWim Vanderbauwhede
 
It was finally Christmas: Perl 6 is here!
It was finally Christmas: Perl 6 is here!It was finally Christmas: Perl 6 is here!
It was finally Christmas: Perl 6 is here!Wim Vanderbauwhede
 
FPGAs as Components in Heterogeneous HPC Systems (paraFPGA 2015 keynote)
FPGAs as Components in Heterogeneous HPC Systems (paraFPGA 2015 keynote) FPGAs as Components in Heterogeneous HPC Systems (paraFPGA 2015 keynote)
FPGAs as Components in Heterogeneous HPC Systems (paraFPGA 2015 keynote) Wim Vanderbauwhede
 
Why I do Computing Science Research
Why I do Computing Science ResearchWhy I do Computing Science Research
Why I do Computing Science ResearchWim Vanderbauwhede
 
On the Capability and Achievable Performance of FPGAs for HPC Applications
On the Capability and Achievable Performance of FPGAs for HPC ApplicationsOn the Capability and Achievable Performance of FPGAs for HPC Applications
On the Capability and Achievable Performance of FPGAs for HPC ApplicationsWim Vanderbauwhede
 

Mehr von Wim Vanderbauwhede (8)

Haku, a toy functional language based on literary Japanese
Haku, a toy functional language  based on literary JapaneseHaku, a toy functional language  based on literary Japanese
Haku, a toy functional language based on literary Japanese
 
Frugal computing
Frugal computingFrugal computing
Frugal computing
 
A few thoughts on work life-balance
A few thoughts on work life-balanceA few thoughts on work life-balance
A few thoughts on work life-balance
 
Greener Search
Greener SearchGreener Search
Greener Search
 
It was finally Christmas: Perl 6 is here!
It was finally Christmas: Perl 6 is here!It was finally Christmas: Perl 6 is here!
It was finally Christmas: Perl 6 is here!
 
FPGAs as Components in Heterogeneous HPC Systems (paraFPGA 2015 keynote)
FPGAs as Components in Heterogeneous HPC Systems (paraFPGA 2015 keynote) FPGAs as Components in Heterogeneous HPC Systems (paraFPGA 2015 keynote)
FPGAs as Components in Heterogeneous HPC Systems (paraFPGA 2015 keynote)
 
Why I do Computing Science Research
Why I do Computing Science ResearchWhy I do Computing Science Research
Why I do Computing Science Research
 
On the Capability and Achievable Performance of FPGAs for HPC Applications
On the Capability and Achievable Performance of FPGAs for HPC ApplicationsOn the Capability and Achievable Performance of FPGAs for HPC Applications
On the Capability and Achievable Performance of FPGAs for HPC Applications
 

Kürzlich hochgeladen

Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptrcbcrtm
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 

Kürzlich hochgeladen (20)

Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.ppt
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 

Perl and Haskell: Can the Twain Ever Meet? (tl;dr: yes)

  • 1. Perl and Haskell: Can the Twain Ever Meet? Wim Vanderbauwhede School of Computing Science, University of Glasgow, UK (tl;dr: yes)
  • 2. Outline Perl Haskell Calling Haskell from Perl C Haskell FFI Perl Inline::C Serialisation What About the Types? The Final Picture The Need for Proper Typing A Modest Proposal Implementation Internals Example Conclusions
  • 3. Perl ... Notorious $_=’while(read+STDIN,$_,2048){$a=29;$b=73; $c=142;$t=255;@t=map{$_%16or$t^=$c^=($m= (11,10,116,100,11,122,20,100)[$_/16%8])&110; $t^=(72,@z=(64,72,$a^=12*($_%16 -2?0:$m&17)), $b^=$_%64?12:0,@z)[$_%8]}(16..271); if((@a=unx"C*",$_)[20]&48){$h =5;$_=unxb24, join"",@b=map{xB8,unxb8,chr($_^$a[--$h+84])} @ARGV;s/...$/1$&/;$ d=unxV,xb25,$_;$e=256| (ord$b[4])<‌<9|ord$b[3];$d=$d>‌>8^($f=$t& ($d>‌>12^$d>‌>4^$d^$d/8))<‌<17,$e=$e>‌>8^($t &($g=($q=$e>‌>14&7^$e)^$q*8^$q<‌<6))<‌<9,$_= $t[$_]^(($h>‌>=8)+=$f+(~$g&$t))for @a[128..$#a]}print+x"C*",@a}’;s/x/pack+/g; eval; But I like Perl
  • 4.
  • 5. Haskell ... Most empathically not dynamically typed ... Makes easy things hard ... But I like Haskell
  • 6. Haskell ... a reputation of being esoteric Monas Hieroglyphica, (“The Hieroglyphic Monad”), John Dee, Antwerp 1564
  • 7.
  • 9. Calling Haskell from Perl Should be as simple as:
  • 10. Calling Haskell from Perl C, the lingua franca Haskell FFI to call Haskell from C Perl Inline::C to call C from Perl Serialisation
  • 11. Code Generation The call to “use Call::Haskell” triggers extensive code generation: Haskell FFI and serialisation wrappers Corresponding C wrappers and create a C library Inline::C wrapper to call the functions in the C library Perl serialisation wrapper Compile only when Haskell source code has changed, otherwise cache
  • 12. Serialisation JSON? YAML? MessagePack? No: Read and Show Because serialisation needs to be type-aware Serialisation of Perl values is done via a custom showH function uses Haskell type information via Data.Typeable, serialised using show, converted to a Perl datastructure in Haskell and deserialised using eval. De-serialisation of Perl serialised values in Haskell is done via read Serialisation of Haskell values is done via show string generated by show is converted into Perl code in Haskell De-serialisation of Haskell result is done via a custom readH function uses eval and Perl’s autload feature
  • 13. Linking FFI uses ghc as linker Perl requires gcc linker ghc does not compile dynamic libraries by default Lots of fun
  • 14. The Final Picture 1. Perl script calls a 2. Perl serialisation wrapper which calls a 3. Perl Inline::C wrapper which calls a 4. C FFI wrapper which calls a 5. Haskell FFI wrapper which calls a 6. Haskell serialisation wrapper which calls 7. the original Haskell function All wrappers are generated and built automatically on loading Call::Haskell
  • 15. What About the Types? The outlined approach relies on Data.Typeable, Read and Show. Data.Typeable does not provide information on type constructors for algebraic types. So this approach only works for “primitive” types and containers holding primitive types. This is already quite a lot, but it’s not good enough. We could add other types (e.g. Data.Map and Maybe) ad hoc However ...
  • 16. The Need for Proper Typing There is a fundamental issue with variant types. Given following Haskell type: data Qual a = Groot a | Klein a It is impossible to generate the correctly typed value for Haskell unless the value in Perl is also typed with the same information! So we need a type system for Perl...
  • 17. A Modest Proposal I propose to create a type system to type datastructures and function signatures in a dynamically typed language (Perl), without changing anything to the language itself but nevertheless with an acceptable and usable syntax. The types must be compatible with Haskell’s types so that it is possible to call Haskell functions with well-typed arguments and return values. show and read the typed values in Haskell fashion.
  • 18. Basic Functionality Declare the type of a typed variable: tv :: T Construct a typed value from other typed and/or untyped values: tv = TC v Bind a typed value to a typed variable: tv = tv Convert a typed value into an untyped value: v u = tv
  • 19. A Simple Type System The type system provides: The primitive scalar types Int, Float, String, Bool. type TI = Int type TF = Float The container types Tuple, Array and Map: type TT = (T1, T2, ..., TN ) type TA = [T1] type TM = {Tk , Tv } A mechanism to declare and construct sum and product types: data TS = T1 | T2 ... TN data TP = TCP T1 ... TN
  • 20. Implementation To implement this type system in Perl, we use functions for the type constructors, a small API of type naming, binding and construction functions. prototypes to construct the actual types. Prototypes are functions that return a type descriptor. lightweight objects to represent the typed values and the type descriptors returned by the prototypes. The implementation relies on two language features: a function can query the name of its callers (caller in Perl) data structures can be transformed into lightweight objects (bless in Perl)
  • 21. newtype and typename To create type constructors: TC = newtype T (Prototype T1...TN ) If the type T is polymorphic, the type name can take parameters: TC = newtype (T a b) (Prototype a b) Also used for container types TC = newtype T (Prototype T1...TN ) And to create an alias for an existing primitive type T = newtype Tprim To declare the type name T T = typename
  • 22. Prototypes Algebraic datatypes: Record: For product types, with optional support for named fields Variant: For sum types Container types: Tuple: For tuples Array: For lists Map: For dictionaries Functions: Function To construct primitive types: Scalar
  • 23. type and bind To declare a typed variable type tv T If the type is a polymorphic type, we can provide the type argument: type tv (T T1) To bind a typed variable to a value, we use bind, which corresponds to “=” in Haskell. bind tv tv If the type of a typed variable is primitive, bind can take an untyped value as the argument: bind tv v
  • 24. untype, show and read To return an untyped value from a typed value v = untype tv Finally, read and show work as in Haskell
  • 25. Internals: Type Names and Prototypes Type Names The typename function returns a tuple of the name of the type and a list of the names parameters, if any. For example, given Couldbe = typename then the call Couldbe a b will return the tuple (Couldbe, [a,b]). Prototypes The prototypes take type name functions as arguments, and return a type descriptor, implemented as a lightweight object. Prototypes can only be called as argument to newtype, which in its turn can only be called in the body of a type constructor function. For example: IntVar = typename MkIntVar = newtype IntVar (Record String Int) The call to Record will return and object of type Record with as attributes the type constructor name and a list of arguments to the constructor, i.e. typenames
  • 26. Internals: Typed Value Objects and Type Construction Typed Value Object An object with attributes Type and Value. The Type attribute contains the information returned by the typename or prototype calls, the Value attribute is populated by a call to newtype or bind. Type Construction The call to newtype typechecks the arguments against the type information returned by the prototype, and returns a typed value object, with the Type field provided by the prototype.
  • 27. Internals: Typing and Binding The call to type returns a typed value object with empty Value attribute, to be filled by a call to bind. The call to bind takes a value, typechecks it and stores it in the Value attribute of the typed value. If the type is a primitive type or a container type holding primitive types, then the value can be untyped and is stored as-is in the Value attribute. In that case, the only checking that is performed is on the type of the container. Otherwise, the value must be typed and will be typechecked.
  • 28. Internals: Typing and Binding For example: type iv IntVar bind iv (MkIntVar “55” 7188 ) The call to MkIntVar will return a typed value object with as Type attribute a Record object with typename IntVar. The typed value iv will contain as Type attribute a tuple with as first argument the typename IntVar. Type checking is simply a comparison of the typenames. In a simpler example: type iv’ Int bind iv’ (Int 42) the call to (Int 42) would return a typed value object, and the bind call would typecheck the typename from the Type attribute with the typename from iv’
  • 29. Function Types We often want to create typed functions from untyped functions. type f Int -> Int -> Int bind f (x y ->x+y) But an untyped function can still take and return typed values: type f (Int,Int) -> Maybe Int bind f ((x,y) -> if (y/=0) then Just x/y else Nothing) We allow both bare and typed values for the argument, and return typed values from the function. The call to bind creates a new function which takes typed arguments, typechecks, untypes them if required, passes them to the original function, and types the return value if required.
  • 30. Polymorphic Binary Tree Example Polymorphic Binary Tree Tree = typename Branch = newtype (Tree a) (Variant Tree a Tree) Leaf = newtype (Tree a) Variant type tree Tree(Int) bind tree (Branch (Branch Leaf 41 Leaf) 42 Leaf) Actual Perl code:
  • 31. Typed Function Call Example use Call::Haskell import => 'VarDeclParser( parse_vardecl )'; use Types; use VarDecl; my $tstr = String("integer :: v"); type my $fp = String => VarDecl; bind $fp, &parse_vardecl; my $tres = $fp−>($tstr); say show $tres; my $res = untype $tres;
  • 32. Summary Want proper typechecking in Perl? https://github.com/wimvanderbauwhede/Perl-Functional-Types Want to call Haskell from Perl? https://github.com/wimvanderbauwhede/Perl-Call-Haskell