Ethiopian multiplication in Perl6

53
Hyper-Multiplying Ethiopians: Lambdas, Lazyness, & Perl6 Steven Lembark Workhorse Computing [email protected]

description

Perl6 introduces a variety of tools for functional programming and generating readable code in all cases. Among them parameter declarations and lazy lists. This talk looks at how to get Perl6, where to find examples on RakudoCode, and how to use the tools for converting an algorithm from imperative to functional code using Perl6, and parallel dispatch with the ">>" operator.

Transcript of Ethiopian multiplication in Perl6

Page 1: Ethiopian multiplication in Perl6

Hyper-Multiplying Ethiopians:Lambdas, Lazyness, & Perl6

Steven LembarkWorkhorse Computing

[email protected]

Page 2: Ethiopian multiplication in Perl6

Welcome to Perl6

Rakudo-Star distro.

Rosetta Code.

Ethiopic Multiplication:

What it is.

More than one way to do it.

Starting with imperative approach.

Perl6 for functional coding?

Page 3: Ethiopian multiplication in Perl6

Rakudo Star: Perl6 in a tarball

Pretty much what you are used to:

Snag a tarball.

perl Configure

make

tests

install

Page 4: Ethiopian multiplication in Perl6

Acquiring Rakudo-Star

Call it “Rakudo” from now on.http://rakudo.org/

Bi-monthly updates are in ./downloads/starwget .../rakudo-star-2014.01.tar.gz;

gzip -dc < *.tar.gz | tar xf -;

cd rakudo-star-2014.01;

less README;

Page 5: Ethiopian multiplication in Perl6

Acquiring Rakudo-Star

Call it “Rakudo” from now on.http://rakudo.org/

Bi-monthly updates are in ./downloads/starwget .../rakudo-star-2013.10.tar.gz;

gzip -dc < *.tar.gz | tar xf -;

cd rakudo-star-2013.10;

perl Configure.pl –build-parrot;

gmake;

gmake rakudo-test;

gmake install;

Page 6: Ethiopian multiplication in Perl6

Information on Perl6

rakudo.org has links to everything else Perl6-ish.

Rakudo's own doc's page is at:

<http://rakudo.org/documentation>

Also the Perl Maven: Gabor Szabo

<http://perl6maven.com/>

For example:

./parsing-command-line-arguments-perl6

Page 7: Ethiopian multiplication in Perl6

Rosetta Code

Wonderful site, if you care about languages.

Various algorithms, variety of languages.

Perl6 versions largely coded by Larry Wall.

Page 8: Ethiopian multiplication in Perl6

Ethiopian Multiplicationhttp://rosettacode.org/wiki/Ethiopian_Multiplication

Developed in the time of roman numerals:

MCMXIV * XXXIIV = ??

Using integer math:

Halve the first number to 1, doubling the second one.

Sum doubled numbers if the halved ones are odd.

Page 9: Ethiopian multiplication in Perl6

Maybe an example will help...

17 x 34 write down two numbers...

Page 10: Ethiopian multiplication in Perl6

Maybe an example will help...

17 x 34

8 halve the first number to 1

4 using integer math...

2

1

Page 11: Ethiopian multiplication in Perl6

Maybe an example will help...

17 x 34

8 68

4 136 double the second number...

2 272

1 544

Page 12: Ethiopian multiplication in Perl6

Maybe an example will help...

17 34

8 68

4 136

2 272

1 544 sum the doubles with odd halves...

Page 13: Ethiopian multiplication in Perl6

Maybe an example will help...

17 34

8 68

4 136

2 272

1 544

578 and you have the product.

Page 14: Ethiopian multiplication in Perl6

Plan 1: Imperative programming

Loop over the halved value.

Doubling the other.

Summing as you go.

Page 15: Ethiopian multiplication in Perl6

What it looks like in Perl5

sub halve { int((shift) / 2) }sub double { (shift) * 2 }sub iseven { ((shift) & 1) == 0 }

sub ethiopicmult{

my ($plier, $plicand) = @_;my $r = 0;while ($plier >= 1){

$r += $plicand unless iseven $plier;$plier = halve $plier;$plicand = double $plicand;

}return $r;

}

Page 16: Ethiopian multiplication in Perl6

Perl6

More ways to do it:

Parameter types.

Local functions.

Page 17: Ethiopian multiplication in Perl6

Stand-alone subs

sub halve  (Int $n is rw)    { $n div= 2 } # integer dividesub double (Int $n is rw)    { $n *= 2  }sub even   (Int $n ­­> Bool) { $n %% 2  } # is­divisible

sub ethiopicmult(

Int $a is copy, Int $b is copy ­­> Int){

my $r = 0;while $a{

even   $a or $r += $b;halve  $a;double $b;

}return $r;

}

Page 18: Ethiopian multiplication in Perl6

Embedded subssub ethiopicmult(

Int $a is copy, Int $b is copy ­­> Int){

sub halve  (Int $n is rw)    { $n div= 2 }; # subs are sub double (Int $n is rw)    { $n *= 2  }; # lexicallysub even   (Int $n ­­> Bool) { $n %% 2  }; # scopedmy $r = 0;

while $a{

even   $a or $r += $b;halve  $a;double $b;

}return $r;

}

Page 19: Ethiopian multiplication in Perl6

Self-contained with lexical subssub ethiopicmult(

Int $a is copy, Int $b is copy ­­> Int){

my &halve = * div= 2; # placeholders savemy &double = * *=   2; # syntax.my &even = * %%   2;my  $r = 0;

loop # a.k.a. for(;;){

even   $a or $r += $b;halve  $a or return $r;double $b;

}}

Page 20: Ethiopian multiplication in Perl6

Self-contained with lexical subssub ethiopicmult(

Int $a is copy, Int $b is copy ­­> Int){

state &halve = * div= 2; # “state” avoids state &double = * *=   2; # re­compiling.state &even = * %%   2;my $r = 0;

loop{

even   $a or $r += $b;halve  $a or return $r;double $b;

}}

Page 21: Ethiopian multiplication in Perl6

Even more than...

Functional Programming:

Yet Another Way to Avoid Spaghetti Code.

Neither “structured programming” nor “objects”.

Manage issues with state and side effects.

Page 22: Ethiopian multiplication in Perl6

The Evil State

State is hard to maintain.

Coding errors: loosing, failed, multiple updates...

Avoiding it reduces errors.

Page 23: Ethiopian multiplication in Perl6

Unintended Consequences

One bad paste:    loop

    {

      double $b;

      even   $a or $r += $b;

      halve  $a or return $r;

      double $b;

    }

Page 24: Ethiopian multiplication in Perl6

“Functional” programming

e.g., Haskell, Scheme, Scala, Clojure

Declarative: describe the answer more so than steps.

(e.g., order of execution in Haskell is derived).

Page 25: Ethiopian multiplication in Perl6

Ideal: pure functional code

Fully deterministic function calls.

No surprises.

Easy to test, with full validation.

Page 26: Ethiopian multiplication in Perl6

Catch: it doesn't work

Examples?

Current time.

Database query.

Random number.

User input.

Result: Be realistic in applying the theory.

Isolate state, don't eliminate it.

Page 27: Ethiopian multiplication in Perl6

Looking at it in Perl6

Replace steps with declarations.

Don't say “how” say “what”.

Page 28: Ethiopian multiplication in Perl6

Declarative definition

sum a list ...

Page 29: Ethiopian multiplication in Perl6

Declarative definition

sum a list ...

selecting the doubled values whose halved entry is odd ...

Page 30: Ethiopian multiplication in Perl6

Declarative definition

sum a list ...

selecting the doubled values whose halved entry is odd ...

from a list of pairs ...

Page 31: Ethiopian multiplication in Perl6

Declarative definition

sum a list ...

selecting the doubled values whose halved entry is odd ...

from a list of pairs ...

halving the first value to one,

doubling the second one each time.

Page 32: Ethiopian multiplication in Perl6

Iterators & maps & zips, oh my!sub ethiopicmult( Int $a is copy, Int $b is copy ­­> Int ){

state &halve = * div= 2;state &double = * *=   2;state &odd = * %    2;

[+] # iterate '+'.map # map pulls two values each time.{

$^col_2 if odd $^col_1 # parameters extract in lexical order.},zip # new list from the list arguments(

$a, &halve  ... 1 ; # semi­colon separates lists$b, &double ... * # indefinate lazy list

);}

Page 33: Ethiopian multiplication in Perl6

Inline list generators replace subs# what you see is all you get:

sub ethiopicmult( Int $a is copy, Int $b is copy ­­> Int ){

[+]map ­> $half, $dbl { $dbl if $half % 2 },zip(

$a, * div 2 ... 0 ; # implicit subs$b, * *   2 ... *

)}

Page 34: Ethiopian multiplication in Perl6

Result

Minimal, declarative syntax.

Avoid order-of-execution errors.

Hopefully more descriptive, easier to maintain.

Page 35: Ethiopian multiplication in Perl6

Result

Minimal, declarative syntax.

Avoid order-of-execution errors.

Hopefully more descriptive, easier to maintain.

But wait!

There's More!

Page 36: Ethiopian multiplication in Perl6

What you are used to

Processing a list with map:

@result = map { $_->$method( @argz ) } @inputs;

- Single-threaded.

- Fixed order of input.

- Fixed order of processing.

Page 37: Ethiopian multiplication in Perl6

Perl6 adds “hyperoperators”

The “»” or “>>” executes its arguments in parallel:

@result = @objects».&function( @args );

@objects might be blessed or class, literal or variable.

@result is stored in the same order as @objects.

The order of execution is indeterminate.

Page 38: Ethiopian multiplication in Perl6

Zipping pairs, not flat lists.“zip” generates a flat list, we need single vlaues.

Infix “Z=>” normally used for hashes:

my %hash =

( ( $a, * div 2 … 0 ) Z=> ( $b, * * 2 … * ) );

Result is a list of key:value “pairs”:( ( 17, 34 ) ; ( ( 8, 68 ) ; … ) 

Page 39: Ethiopian multiplication in Perl6

Processing pairs

Pair object has a “key” and “value”:

sub odd_values( $pair )

{

$pair.key % 2  ?? $pair.value !! () }

Which leaves us with the values that have to be summed.

Page 40: Ethiopian multiplication in Perl6

Generating the list of odd values

The result of calling “odd_values” is summed just as before:

[+] 

( ( $a, * div 2 … 0 ) Z=> ( $b, * * 2 … * ) )\ ».odd_values

Selection of odd values is parallel.

Generation of pairs and sum are single-threaded.

Page 41: Ethiopian multiplication in Perl6

Reading on the ceiling

Catch: map-ish code reads “upside down”.

Ever wish you could read it going down the page?

Page 42: Ethiopian multiplication in Perl6

Standing on your own two feet

Wish no more: the “Feed operator” pushes the list downhill:

( ( $a, * div 2 … 0 ) Z=> ( $b, * * 2 … * ) )\ ».odd_values ==> [+]

The feed operator shows the direction of data flow.

Feeds odds_values parallel results to block-iterator on '+'.

Page 43: Ethiopian multiplication in Perl6

The result

sub ethiopic_mult( $a, $b )

{

    sub odd_values( $pair ) 

    { $pair.key % 2 ?? $pair.value :: () }

    (( $a, * div 2 ... 0 ) Z=> ( $b, * * 2 ... ) ))\

    >>.&odd_values ==> [+]

}

Page 44: Ethiopian multiplication in Perl6

Hyper-whybotherators?

“$a % 2” is low overhead.

Say you were comparing DNA or proteins...

… running a complex financial calculation...

… playing conway's game of life?

Wouldn't it be nice to queue the operations without loops, forks, breaks, joins, co‑routines, or queues?

Page 45: Ethiopian multiplication in Perl6

What's this got to do with FP?

Hyperoperators lack repeatable sequence.

No way to know order of side effects or state updates.

Manipulating state or side effects don't work.

Simple fix: Use FP [-ish] functions for hyperoperators.

Page 46: Ethiopian multiplication in Perl6

New things in Perl6

%% is “Divisible By” (vs. % for “modulo”).

my &subname = ... for lexically defined subs.

* for parameters.

$^foo for block parameters.

Integer division with 'div'.

Parameterized lists with $start, OP, $end.

List operators with [ OP ].

Hyperopertors & friends.

Page 47: Ethiopian multiplication in Perl6

References

Monads in Perl5:

<http://web.archive.org/web/20080515195640/http://sleepingsquirrel.org/monads/monads.html>

Introduces the basic ideas of functional programming with monads using Perl5 examples.

Page 48: Ethiopian multiplication in Perl6

References

Readable descriptions of “Monad”:

<https://stackoverflow.com/questions/44965/what-is-a-monad>

<https://stackoverflow.com/questions/2704652/monad-in-plain-english-for-the-oop-programmer-with-no-fp-background>

Page 49: Ethiopian multiplication in Perl6

References

What databases mean to Functional Programming:

<https://stackoverflow.com/questions/8406261/most-common-pattern-for-using-a-database-in-a-functional-language-given-desire>

“The most common pattern for dealing with side-effects and impurity in functional languages is:

- be pragmatic, not a purist ...”

Page 50: Ethiopian multiplication in Perl6

References

Realistic view of FP:

<https://stackoverflow.com/questions/330371/are-databases-and-functional-programming-at-odds>

“Functional languages do not have the goal to remain stateless, they have the goal to make management of state explicit.”

Page 51: Ethiopian multiplication in Perl6

References

Good overview of the vocabulary:

<http://en.wikipedia.org/wiki/Functional_Programming>

Page 52: Ethiopian multiplication in Perl6

References

Academic description of Monads:

<http://web.archive.org/web/20071128090030/http://homepages.inf.ed.ac.uk/wadler/papers/marktoberdorf/baastad.pdf>

Page 53: Ethiopian multiplication in Perl6