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

Wim Vanderbauwhede
Wim VanderbauwhedeComputing Scientist at University of Glasgow em University of Glasgow
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
Perl and Haskell: Can the Twain Ever Meet? (tl;dr: yes)
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
Perl and Haskell: Can the Twain Ever Meet? (tl;dr: yes)
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?
1 de 33

Recomendados

List-based Monadic Computations for Dynamic Languages por
List-based Monadic Computations for Dynamic LanguagesList-based Monadic Computations for Dynamic Languages
List-based Monadic Computations for Dynamic LanguagesWim Vanderbauwhede
20.3K visualizações46 slides
List-based Monadic Computations for Dynamically Typed Languages (Python version) por
List-based Monadic Computations for Dynamically Typed Languages (Python version)List-based Monadic Computations for Dynamically Typed Languages (Python version)
List-based Monadic Computations for Dynamically Typed Languages (Python version)Wim Vanderbauwhede
27.4K visualizações45 slides
Real World Haskell: Lecture 5 por
Real World Haskell: Lecture 5Real World Haskell: Lecture 5
Real World Haskell: Lecture 5Bryan O'Sullivan
1.2K visualizações24 slides
Reasoning about laziness por
Reasoning about lazinessReasoning about laziness
Reasoning about lazinessJohan Tibell
3.7K visualizações29 slides
Real World Haskell: Lecture 4 por
Real World Haskell: Lecture 4Real World Haskell: Lecture 4
Real World Haskell: Lecture 4Bryan O'Sullivan
1.2K visualizações34 slides
Real World Haskell: Lecture 6 por
Real World Haskell: Lecture 6Real World Haskell: Lecture 6
Real World Haskell: Lecture 6Bryan O'Sullivan
1.7K visualizações38 slides

Mais conteúdo relacionado

Mais procurados

Scala categorytheory por
Scala categorytheoryScala categorytheory
Scala categorytheoryKnoldus Inc.
1.4K visualizações22 slides
Clojure basics por
Clojure basicsClojure basics
Clojure basicsKnoldus Inc.
3.6K visualizações26 slides
The Functional Programming Triad of Folding, Scanning and Iteration - a first... por
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
970 visualizações31 slides
Real World Haskell: Lecture 7 por
Real World Haskell: Lecture 7Real World Haskell: Lecture 7
Real World Haskell: Lecture 7Bryan O'Sullivan
1.4K visualizações34 slides
Real World Haskell: Lecture 3 por
Real World Haskell: Lecture 3Real World Haskell: Lecture 3
Real World Haskell: Lecture 3Bryan O'Sullivan
1.2K visualizações38 slides
Monad Fact #4 por
Monad Fact #4Monad Fact #4
Monad Fact #4Philip Schwarz
384 visualizações24 slides

Mais procurados(20)

Scala categorytheory por Knoldus Inc.
Scala categorytheoryScala categorytheory
Scala categorytheory
Knoldus Inc.1.4K visualizações
Clojure basics por Knoldus Inc.
Clojure basicsClojure basics
Clojure basics
Knoldus Inc.3.6K visualizações
The Functional Programming Triad of Folding, Scanning and Iteration - a first... por Philip Schwarz
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 Schwarz970 visualizações
Real World Haskell: Lecture 7 por Bryan O'Sullivan
Real World Haskell: Lecture 7Real World Haskell: Lecture 7
Real World Haskell: Lecture 7
Bryan O'Sullivan1.4K visualizações
Real World Haskell: Lecture 3 por Bryan O'Sullivan
Real World Haskell: Lecture 3Real World Haskell: Lecture 3
Real World Haskell: Lecture 3
Bryan O'Sullivan1.2K visualizações
Monad Fact #4 por Philip Schwarz
Monad Fact #4Monad Fact #4
Monad Fact #4
Philip Schwarz384 visualizações
Real World Haskell: Lecture 1 por Bryan O'Sullivan
Real World Haskell: Lecture 1Real World Haskell: Lecture 1
Real World Haskell: Lecture 1
Bryan O'Sullivan1.8K visualizações
3 kotlin vs. java- what kotlin has that java does not por Sergey Bandysik
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
Sergey Bandysik294 visualizações
The string class por Syed Zaid Irshad
The string classThe string class
The string class
Syed Zaid Irshad1.9K visualizações
Big picture of category theory in scala with deep dive into contravariant and... por Piotr Paradziński
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ński840 visualizações
Function Applicative for Great Good of Palindrome Checker Function - Polyglot... por Philip Schwarz
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 Schwarz1.5K visualizações
Applicative Functor - Part 3 por Philip Schwarz
Applicative Functor - Part 3Applicative Functor - Part 3
Applicative Functor - Part 3
Philip Schwarz648 visualizações
Bc0037 por hayerpa
Bc0037Bc0037
Bc0037
hayerpa312 visualizações
Implicit conversion and parameters por Knoldus Inc.
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parameters
Knoldus Inc.1.2K visualizações
Scala 3 enum for a terser Option Monad Algebraic Data Type por Philip Schwarz
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
Philip Schwarz581 visualizações
Strinng Classes in c++ por Vikash Dhal
Strinng Classes in c++Strinng Classes in c++
Strinng Classes in c++
Vikash Dhal1.3K visualizações
Introducing Assignment invalidates the Substitution Model of Evaluation and v... por Philip Schwarz
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 Schwarz623 visualizações
Let's make a contract: the art of designing a Java API por Mario Fusco
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
Mario Fusco2.7K visualizações
C++ theory por Shyam Khant
C++ theoryC++ theory
C++ theory
Shyam Khant8.2K visualizações

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

C# Summer course - Lecture 2 por
C# Summer course - Lecture 2C# Summer course - Lecture 2
C# Summer course - Lecture 2mohamedsamyali
553 visualizações23 slides
Savitch Ch 17 por
Savitch Ch 17Savitch Ch 17
Savitch Ch 17Terry Yoast
355 visualizações46 slides
unit 1.docx por
unit 1.docxunit 1.docx
unit 1.docxssuser2e84e4
13 visualizações30 slides
All About ... Functions por
All About ... FunctionsAll About ... Functions
All About ... FunctionsMichal Bigos
792 visualizações63 slides
CS-XII Python Fundamentals.pdf por
CS-XII Python Fundamentals.pdfCS-XII Python Fundamentals.pdf
CS-XII Python Fundamentals.pdfIda Lumintu
9 visualizações7 slides
DAY_1.3.pptx por
DAY_1.3.pptxDAY_1.3.pptx
DAY_1.3.pptxishasharma835109
1 visão23 slides

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

C# Summer course - Lecture 2 por mohamedsamyali
C# Summer course - Lecture 2C# Summer course - Lecture 2
C# Summer course - Lecture 2
mohamedsamyali553 visualizações
Savitch Ch 17 por Terry Yoast
Savitch Ch 17Savitch Ch 17
Savitch Ch 17
Terry Yoast355 visualizações
unit 1.docx por ssuser2e84e4
unit 1.docxunit 1.docx
unit 1.docx
ssuser2e84e413 visualizações
All About ... Functions por Michal Bigos
All About ... FunctionsAll About ... Functions
All About ... Functions
Michal Bigos792 visualizações
CS-XII Python Fundamentals.pdf por Ida Lumintu
CS-XII Python Fundamentals.pdfCS-XII Python Fundamentals.pdf
CS-XII Python Fundamentals.pdf
Ida Lumintu9 visualizações
Savitch ch 17 por Terry Yoast
Savitch ch 17Savitch ch 17
Savitch ch 17
Terry Yoast316 visualizações
Scala Paradigms por Tom Flaherty
Scala ParadigmsScala Paradigms
Scala Paradigms
Tom Flaherty1.7K visualizações
Back to the Future with TypeScript por Aleš Najmann
Back to the Future with TypeScriptBack to the Future with TypeScript
Back to the Future with TypeScript
Aleš Najmann452 visualizações
Types, classes and concepts por Nicola Bonelli
Types, classes and conceptsTypes, classes and concepts
Types, classes and concepts
Nicola Bonelli1.3K visualizações
Scala Back to Basics: Type Classes por Tomer Gabel
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
Tomer Gabel3.7K visualizações
C Types - Extending Python por Priyank Kapadia
C Types - Extending PythonC Types - Extending Python
C Types - Extending Python
Priyank Kapadia9.5K visualizações
Core c sharp and .net quick reference por Arduino Aficionado
Core c sharp and .net quick referenceCore c sharp and .net quick reference
Core c sharp and .net quick reference
Arduino Aficionado514 visualizações
Core csharp and net quick reference por ilesh raval
Core csharp and net quick referenceCore csharp and net quick reference
Core csharp and net quick reference
ilesh raval3.2K visualizações
Python variables and data types.pptx por AkshayAggarwal79
Python variables and data types.pptxPython variables and data types.pptx
Python variables and data types.pptx
AkshayAggarwal79386 visualizações
Solid C++ by Example por Olve Maudal
Solid C++ by ExampleSolid C++ by Example
Solid C++ by Example
Olve Maudal20.4K visualizações
Notes(1).pptx por InfinityWorld3
Notes(1).pptxNotes(1).pptx
Notes(1).pptx
InfinityWorld311 visualizações
DATA TYPE IN PYTHON por vikram mahendra
DATA TYPE IN PYTHONDATA TYPE IN PYTHON
DATA TYPE IN PYTHON
vikram mahendra77 visualizações
Type Driven Development with TypeScript por Garth Gilmour
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScript
Garth Gilmour388 visualizações

Mais de Wim Vanderbauwhede

Haku, a toy functional language based on literary Japanese por
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
10.5K visualizações45 slides
Frugal computing por
Frugal computingFrugal computing
Frugal computingWim Vanderbauwhede
7.8K visualizações21 slides
A few thoughts on work life-balance por
A few thoughts on work life-balanceA few thoughts on work life-balance
A few thoughts on work life-balanceWim Vanderbauwhede
1.8M visualizações40 slides
Greener Search por
Greener SearchGreener Search
Greener SearchWim Vanderbauwhede
23.6K visualizações25 slides
It was finally Christmas: Perl 6 is here! por
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
22.8K visualizações52 slides
FPGAs as Components in Heterogeneous HPC Systems (paraFPGA 2015 keynote) por
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
20.8K visualizações62 slides

Mais de Wim Vanderbauwhede(8)

Haku, a toy functional language based on literary Japanese por Wim Vanderbauwhede
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
Wim Vanderbauwhede10.5K visualizações
Frugal computing por Wim Vanderbauwhede
Frugal computingFrugal computing
Frugal computing
Wim Vanderbauwhede7.8K visualizações
A few thoughts on work life-balance por Wim Vanderbauwhede
A few thoughts on work life-balanceA few thoughts on work life-balance
A few thoughts on work life-balance
Wim Vanderbauwhede1.8M visualizações
Greener Search por Wim Vanderbauwhede
Greener SearchGreener Search
Greener Search
Wim Vanderbauwhede23.6K visualizações
It was finally Christmas: Perl 6 is here! por Wim 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!
Wim Vanderbauwhede22.8K visualizações
FPGAs as Components in Heterogeneous HPC Systems (paraFPGA 2015 keynote) por 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)
Wim Vanderbauwhede20.8K visualizações
Why I do Computing Science Research por Wim Vanderbauwhede
Why I do Computing Science ResearchWhy I do Computing Science Research
Why I do Computing Science Research
Wim Vanderbauwhede28.8K visualizações
On the Capability and Achievable Performance of FPGAs for HPC Applications por Wim Vanderbauwhede
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
Wim Vanderbauwhede14.6K visualizações

Último

LAVADORA ROLO.docx por
LAVADORA ROLO.docxLAVADORA ROLO.docx
LAVADORA ROLO.docxSamuelRamirez83524
7 visualizações1 slide
Mark Simpson - UKOUG23 - Refactoring Monolithic Oracle Database Applications ... por
Mark Simpson - UKOUG23 - Refactoring Monolithic Oracle Database Applications ...Mark Simpson - UKOUG23 - Refactoring Monolithic Oracle Database Applications ...
Mark Simpson - UKOUG23 - Refactoring Monolithic Oracle Database Applications ...marksimpsongw
76 visualizações34 slides
DSD-INT 2023 Modelling litter in the Yarra and Maribyrnong Rivers (Australia)... por
DSD-INT 2023 Modelling litter in the Yarra and Maribyrnong Rivers (Australia)...DSD-INT 2023 Modelling litter in the Yarra and Maribyrnong Rivers (Australia)...
DSD-INT 2023 Modelling litter in the Yarra and Maribyrnong Rivers (Australia)...Deltares
9 visualizações34 slides
DSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - Geertsema por
DSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - GeertsemaDSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - Geertsema
DSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - GeertsemaDeltares
17 visualizações13 slides
Elevate your SAP landscape's efficiency and performance with HCL Workload Aut... por
Elevate your SAP landscape's efficiency and performance with HCL Workload Aut...Elevate your SAP landscape's efficiency and performance with HCL Workload Aut...
Elevate your SAP landscape's efficiency and performance with HCL Workload Aut...HCLSoftware
6 visualizações2 slides
Upgrading Incident Management with Icinga - Icinga Camp Milan 2023 por
Upgrading Incident Management with Icinga - Icinga Camp Milan 2023Upgrading Incident Management with Icinga - Icinga Camp Milan 2023
Upgrading Incident Management with Icinga - Icinga Camp Milan 2023Icinga
38 visualizações17 slides

Último(20)

Mark Simpson - UKOUG23 - Refactoring Monolithic Oracle Database Applications ... por marksimpsongw
Mark Simpson - UKOUG23 - Refactoring Monolithic Oracle Database Applications ...Mark Simpson - UKOUG23 - Refactoring Monolithic Oracle Database Applications ...
Mark Simpson - UKOUG23 - Refactoring Monolithic Oracle Database Applications ...
marksimpsongw76 visualizações
DSD-INT 2023 Modelling litter in the Yarra and Maribyrnong Rivers (Australia)... por Deltares
DSD-INT 2023 Modelling litter in the Yarra and Maribyrnong Rivers (Australia)...DSD-INT 2023 Modelling litter in the Yarra and Maribyrnong Rivers (Australia)...
DSD-INT 2023 Modelling litter in the Yarra and Maribyrnong Rivers (Australia)...
Deltares9 visualizações
DSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - Geertsema por Deltares
DSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - GeertsemaDSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - Geertsema
DSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - Geertsema
Deltares17 visualizações
Elevate your SAP landscape's efficiency and performance with HCL Workload Aut... por HCLSoftware
Elevate your SAP landscape's efficiency and performance with HCL Workload Aut...Elevate your SAP landscape's efficiency and performance with HCL Workload Aut...
Elevate your SAP landscape's efficiency and performance with HCL Workload Aut...
HCLSoftware6 visualizações
Upgrading Incident Management with Icinga - Icinga Camp Milan 2023 por Icinga
Upgrading Incident Management with Icinga - Icinga Camp Milan 2023Upgrading Incident Management with Icinga - Icinga Camp Milan 2023
Upgrading Incident Management with Icinga - Icinga Camp Milan 2023
Icinga38 visualizações
A first look at MariaDB 11.x features and ideas on how to use them por Federico Razzoli
A first look at MariaDB 11.x features and ideas on how to use themA first look at MariaDB 11.x features and ideas on how to use them
A first look at MariaDB 11.x features and ideas on how to use them
Federico Razzoli45 visualizações
ict act 1.pptx por sanjaniarun08
ict act 1.pptxict act 1.pptx
ict act 1.pptx
sanjaniarun0813 visualizações
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx por animuscrm
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx
animuscrm13 visualizações
El Arte de lo Possible por Neo4j
El Arte de lo PossibleEl Arte de lo Possible
El Arte de lo Possible
Neo4j38 visualizações
Advanced API Mocking Techniques por Dimpy Adhikary
Advanced API Mocking TechniquesAdvanced API Mocking Techniques
Advanced API Mocking Techniques
Dimpy Adhikary19 visualizações
.NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra... por Marc Müller
.NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra....NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra...
.NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra...
Marc Müller38 visualizações
Software testing company in India.pptx por SakshiPatel82
Software testing company in India.pptxSoftware testing company in India.pptx
Software testing company in India.pptx
SakshiPatel827 visualizações
DevsRank por devsrank786
DevsRankDevsRank
DevsRank
devsrank78611 visualizações
DSD-INT 2023 3D hydrodynamic modelling of microplastic transport in lakes - J... por Deltares
DSD-INT 2023 3D hydrodynamic modelling of microplastic transport in lakes - J...DSD-INT 2023 3D hydrodynamic modelling of microplastic transport in lakes - J...
DSD-INT 2023 3D hydrodynamic modelling of microplastic transport in lakes - J...
Deltares9 visualizações
DSD-INT 2023 - Delft3D User Days - Welcome - Day 3 - Afternoon por Deltares
DSD-INT 2023 - Delft3D User Days - Welcome - Day 3 - AfternoonDSD-INT 2023 - Delft3D User Days - Welcome - Day 3 - Afternoon
DSD-INT 2023 - Delft3D User Days - Welcome - Day 3 - Afternoon
Deltares13 visualizações
SUGCON ANZ Presentation V2.1 Final.pptx por Jack Spektor
SUGCON ANZ Presentation V2.1 Final.pptxSUGCON ANZ Presentation V2.1 Final.pptx
SUGCON ANZ Presentation V2.1 Final.pptx
Jack Spektor22 visualizações
Unleash The Monkeys por Jacob Duijzer
Unleash The MonkeysUnleash The Monkeys
Unleash The Monkeys
Jacob Duijzer7 visualizações
Dev-Cloud Conference 2023 - Continuous Deployment Showdown: Traditionelles CI... por Marc Müller
Dev-Cloud Conference 2023 - Continuous Deployment Showdown: Traditionelles CI...Dev-Cloud Conference 2023 - Continuous Deployment Showdown: Traditionelles CI...
Dev-Cloud Conference 2023 - Continuous Deployment Showdown: Traditionelles CI...
Marc Müller36 visualizações
SAP FOR TYRE INDUSTRY.pdf por Virendra Rai, PMP
SAP FOR TYRE INDUSTRY.pdfSAP FOR TYRE INDUSTRY.pdf
SAP FOR TYRE INDUSTRY.pdf
Virendra Rai, PMP23 visualizações

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
  • 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
  • 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