SlideShare a Scribd company logo
Functional Pe(a)rls



          osfameron @ IPW2011, Turin
      the “purely functional data structures”
                     edition

http://www.fickr.com/photos/jef_saf/3493852795/
previously on Functional Pe(a)rls...



      (IPW, LPW, YAPC::EU, nwe.pm)
                 currying
         operator references: op(+)
              Acme::Monads
              Devel::Declare
C       I A O
            vs.


C       I         A   O
0       1    2   3


    C       I A O
0        1    2   3


     C        I A O


0th element
0        1   2   3


     M I A O


0th element
0         1         2    3


      M I A O


 0th element
no kittens were harmed
  during the making of
       this presentation
0    1    2       3


    M I A O


         2nd element
0    1   2   3


    M I A O


                 4th element
0    1   2   3


    M I A O
max: 3
0    1   2   3


    M I A O
max: 3
0    1   2   3   4

    M I A O W
max: 4

                 4th element
max: 3
0 1 2 3       100,000
M I A O
          …
0    1   2   3


    M I A O
max: 3
0    1   2   3   4

    M I A O W
max: 4


0    1   2   3   4   5


    M I A O W !
max: 5
0    1   2   3   4

    M I A O W
max: 4


0    1   2   3   4   5


    M I A O W !
max: 5
Arrays

    C       I A O
            vs.


C       I         A       O
Perl @arrays

    C       I A O
                      “dynamic array”




            vs.


C       I         A       O
C   I   A   O
C   I   A   O
C     I   A   O
Head
C    I     A   O
    Tail
C   I   A   O
C   I   A   O
I   A   O
A   O
O
C     I   A   O

0th
C     I       A   O

    nth - 1
C          I        A   O

nth[2]?   nth[1]?
C         I   A         O

nth[2]?       nth[0]!
C   I   A   O
                ?
●
    C             I
    tail “ciao” → “iao”
                          A   O
                                  ?
●
    C             I
    tail “ciao” → “iao”
                          A   O
                                  ?
●   tail “iao” → “ao”
●   tail “ao” → “o”
●   tail “o” → ?
●
    C             I
    tail “ciao” → “iao”
                               A       O
                                           ?
●   tail “iao” → “ao”
●   tail “ao” → “o”
●   tail “o” → “” (the empty string)
C   I   A   O
List =

Head           Tail
               (another List)


       or...
Here comes the science^wPerl!
Moose(X::Declare)
use MooseX::Declare;

BEGIN { role_type 'List' }

role List {
     requires 'head';
     requires 'tail';
}
List::Link
class List::Link with List {
  has head => (
       is => 'ro',
       isa => 'Any'
   );
  has tail => (
       is => 'ro',
       isa => 'List'
    ),
}
List::Link
class List::Link with List {
  has head => (
       is => 'ro',
       isa => 'Any'
   );
  has tail => (
       is => 'ro',
       isa => 'List'
    ),
}
List::Link
class List::Link with List {
  has head => (
       is => 'ro',
       isa => 'Any'
   );
  has tail => (
       is => 'ro',
       isa => 'List'
    ),
}
List::Empty
class List::Empty with List {
   method head {
     die "Can't take head of empty list!"
   }
   method tail {
     die "Can't take tail of empty list!"
   }
}
So we can write:

my $list = List::Link->new(
    head => 'c',
    tail => List::Link->new(
       head => 'i',
       tail => List::Link->new(...
Sugar!

my $list = List->fromArray(
 qw/ c i a o /);
Multimethods

use MooseX::MultiMethods;

multi method fromArray ($class:) {
  return List::Empty->new;
}
Multimethods

use MooseX::MultiMethods;

multi method fromArray ($class:) {
  return List::Empty->new;
}
Multimethods

multi method fromArray  ($class: $head, @tail) {
    return List::Link->new(
       head => $head,
       tail => $class->fromArray(@tail),
    );
}
Eeek! Recursion!
my $list = List::fromArray(1..1000000);
Eeek! Recursion!
my $list = List::fromArray(1..1000000);

Deep recursion on subroutine
"List::fromArray" at foo.pl line 20
Eeek! Recursion!

multi method fromArray  ($class: $head, @tail) {
    return List::Link->new(
       head => $head,
       tail => $class->fromArray(@tail),
    );
}
Eeek! Recursion!
fromArray
Eeek! Recursion!
fromArray


  List::Link->new
  (..., fromArray)
Eeek! Recursion!
fromArray


  List::Link->new
  (..., fromArray)

            List::Link->new
            (..., fromArray)
Eeek! Recursion!
fromArray


  List::Link->new
  (..., fromArray)

            List::Link->new
            (..., fromArray)

                   List::Link->new
                   (..., fromArray)
Eeek! Recursion!
fromArray


  List::Link->new
  (..., fromArray)

            List::Link->new
            (..., fromArray)

                   List::Link->new
                   (..., fromArray)

                               List::Link->new
                               (..., fromArray)
Eeek! Recursion!
fromArray


  List::Link->new
  (..., fromArray)

            List::Link->new
            (..., fromArray)

                   List::Link->new
                   (..., fromArray)

                               List::Link->new
                               (..., fromArray)   = $list
Eeek! Recursion!
fromArray


  List::Link->new
  (..., fromArray)

            List::Link->new
            (..., fromArray)

                   List::Link->new
                   (..., fromArray)   = $list
Eeek! Recursion!
fromArray


  List::Link->new
  (..., fromArray)

            List::Link->new
            (..., fromArray)   = $list
Eeek! Recursion!
fromArray


  List::Link->new
  (..., fromArray)   = $list
Eeek! Recursion!
fromArray = $list
Eeek! Recursion!

no warnings 'recursion';
$DB::deep = 100_000_000;
Eeek! Recursion!

no warnings 'recursion';
$DB::deep = 100_000_000;

Papering over the cracks
Tail Call Elimination

Sub::Call::Tail
Sub::Call::Recur

by nothingmuch
Tail call elimination
fromArray
Tail call elimination


List::Link->new
(..., fromArray)
Tail call elimination



List::Link->new
(..., fromArray)
Tail call elimination




  List::Link->new
  (..., fromArray)
Tail call elimination




      List::Link->new
      (..., fromArray)
Tail call elimination




      List::Link->new
      (..., fromArray)   = $list
Tail Call Elimination

use Sub::Import 'Sub::Call::Tail'
      tail => { -as => 'tail_call' };

multi method fromArray ($self: $head, @tail)
{
    tail_call List::Link->new(
       head => $head,
       tail => $self->fromArray(@tail),
    );
}
Indexing into List

multi method nth
  (List::Empty $self: Int $pos)
{
  die "Can't index into an Empty list";
}
Indexing into List

 multi method nth
  (Int $pos where { $_ == 0 })
{
  return $self->head;
}
Indexing into List

multi method nth
  (Int $pos where { $_ > 0 })
{
  tail_call $self->tail->nth( $pos - 1 );
}
C   I   A   O

M
C   I   A   O

M               W
C    I              A        O

M                                W
    Mutation leads to bugs
    (and misspellings!)
C   I   A   O

M   I   A   O   W
C   I   A   O

C   I   B
C           I               A              O

C           I              B
    Copy everything upstream of a change
    Downstream of changes can be shared
C            I              A                 O

C           I               B                 O
    Doubly linked lists have no downstream!
pure-fp-book



●   https://github.com/osfameron/pure-fp-book
●   Purely Functional Data Structures for the...
    ●   Impure
    ●   Perl Programmer
    ●   Working Programmer
    ●   Mutable, Rank-Scented Many

More Related Content

PDF
Functional pe(a)rls: Huey's zipper
PDF
Is Haskell an acceptable Perl?
PPT
Functional Pe(a)rls version 2
PDF
Haskell in the Real World
KEY
Exhibition of Atrocity
PDF
Programming Lisp Clojure - 2장 : 클로저 둘러보기
PDF
PHP 7 – What changed internally? (Forum PHP 2015)
PDF
PHP 7 – What changed internally?
Functional pe(a)rls: Huey's zipper
Is Haskell an acceptable Perl?
Functional Pe(a)rls version 2
Haskell in the Real World
Exhibition of Atrocity
Programming Lisp Clojure - 2장 : 클로저 둘러보기
PHP 7 – What changed internally? (Forum PHP 2015)
PHP 7 – What changed internally?

What's hot (20)

PDF
RxSwift 시작하기
PDF
Descobrindo a linguagem Perl
PPT
An Elephant of a Different Colour: Hack
PPTX
Perl6 a whistle stop tour
PDF
Perl6 a whistle stop tour
PDF
The Perl6 Type System
KEY
Invertible-syntax 入門
PDF
Wx::Perl::Smart
KEY
Desarrollando aplicaciones web en minutos
PDF
Frege is a Haskell for the JVM
PDF
Perl 6 in Context
PDF
Introdução ao Perl 6
PDF
Perl.Hacks.On.Vim
PDF
Swift 함수 커링 사용하기
KEY
Template Haskell とか
PPT
PHP and MySQL
KEY
groovy & grails - lecture 3
PDF
Static Optimization of PHP bytecode (PHPSC 2017)
PPTX
第二讲 预备-Python基礎
PPTX
第二讲 Python基礎
RxSwift 시작하기
Descobrindo a linguagem Perl
An Elephant of a Different Colour: Hack
Perl6 a whistle stop tour
Perl6 a whistle stop tour
The Perl6 Type System
Invertible-syntax 入門
Wx::Perl::Smart
Desarrollando aplicaciones web en minutos
Frege is a Haskell for the JVM
Perl 6 in Context
Introdução ao Perl 6
Perl.Hacks.On.Vim
Swift 함수 커링 사용하기
Template Haskell とか
PHP and MySQL
groovy & grails - lecture 3
Static Optimization of PHP bytecode (PHPSC 2017)
第二讲 预备-Python基礎
第二讲 Python基礎
Ad

Similar to Functional Pe(a)rls - the Purely Functional Datastructures edition (20)

PPTX
PHP Functions & Arrays
PDF
Scripting3
PPT
Basic perl programming
PPTX
Switching from java to groovy
PDF
Hypers and Gathers and Takes! Oh my!
PPT
Crash Course in Perl – Perl tutorial for C programmers
PDF
Barcelona.pm Curs1211 sess01
ODP
Writing Maintainable Perl
PDF
Perl 6 by example
PDF
Regexp Master
PPT
computer notes - Data Structures - 32
KEY
1 the ruby way
PPT
Computer notes - Binary Search
PDF
Wheels we didn't re-invent: Perl's Utility Modules
ODP
Intro to The PHP SPL
PDF
PHP 101
KEY
Searching ORM: First Why, Then How
PDF
First steps in PERL
PDF
List Unfolding - 'unfold' as the Computational Dual of 'fold', and how 'unfol...
PHP Functions & Arrays
Scripting3
Basic perl programming
Switching from java to groovy
Hypers and Gathers and Takes! Oh my!
Crash Course in Perl – Perl tutorial for C programmers
Barcelona.pm Curs1211 sess01
Writing Maintainable Perl
Perl 6 by example
Regexp Master
computer notes - Data Structures - 32
1 the ruby way
Computer notes - Binary Search
Wheels we didn't re-invent: Perl's Utility Modules
Intro to The PHP SPL
PHP 101
Searching ORM: First Why, Then How
First steps in PERL
List Unfolding - 'unfold' as the Computational Dual of 'fold', and how 'unfol...
Ad

More from osfameron (11)

PDF
Writing a Tile-Matching Game - FP Style
PPTX
Data Structures for Text Editors
PDF
Rewriting the Apocalypse
PDF
Global Civic Hacking 101 (lightning talk)
PDF
Adventures in civic hacking
PDF
Oyster: an incubator for perls in the cloud
PDF
Semantic Pipes (London Perl Workshop 2009)
ODP
Functional Pearls 4 (YAPC::EU::2009 remix)
PDF
Functional Pe(a)rls
PDF
Readable Perl
PDF
Bigbadwolf
Writing a Tile-Matching Game - FP Style
Data Structures for Text Editors
Rewriting the Apocalypse
Global Civic Hacking 101 (lightning talk)
Adventures in civic hacking
Oyster: an incubator for perls in the cloud
Semantic Pipes (London Perl Workshop 2009)
Functional Pearls 4 (YAPC::EU::2009 remix)
Functional Pe(a)rls
Readable Perl
Bigbadwolf

Recently uploaded (20)

PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PPTX
Cloud computing and distributed systems.
PDF
GDG Cloud Iasi [PUBLIC] Florian Blaga - Unveiling the Evolution of Cybersecur...
PDF
Electronic commerce courselecture one. Pdf
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Empathic Computing: Creating Shared Understanding
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Modernizing your data center with Dell and AMD
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
GamePlan Trading System Review: Professional Trader's Honest Take
PDF
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
PPTX
Big Data Technologies - Introduction.pptx
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
NewMind AI Weekly Chronicles - August'25 Week I
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Cloud computing and distributed systems.
GDG Cloud Iasi [PUBLIC] Florian Blaga - Unveiling the Evolution of Cybersecur...
Electronic commerce courselecture one. Pdf
Network Security Unit 5.pdf for BCA BBA.
MYSQL Presentation for SQL database connectivity
Empathic Computing: Creating Shared Understanding
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Modernizing your data center with Dell and AMD
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Dropbox Q2 2025 Financial Results & Investor Presentation
GamePlan Trading System Review: Professional Trader's Honest Take
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
Big Data Technologies - Introduction.pptx
Spectral efficient network and resource selection model in 5G networks
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...

Functional Pe(a)rls - the Purely Functional Datastructures edition