Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Reactive Programming in Perl6

Reactive Programming in Perl6

Gotanda.pm #9, 2016.06.29

Shoichi Kaji

June 29, 2016
Tweet

More Decks by Shoichi Kaji

Other Decks in Programming

Transcript

  1. Me • Shoichi Kaji • pause/github: skaji • Perl5: cpm,

    App::FatPacker::Simple, Mojo::SlackRTM • Perl6: mi6, Frinfon, evalbot in Slack
  2. Yes

  3. $ crustup -e '-> $e {200, [], ["hello world"]}' http

    server is ready: http://127.0.0.1:5000/ $ curl http://localhost:5000 hello world
  4. # app.p6 use v6; use Frinfon; get "/" => sub

    ($c) { $c.render-text("hello world\n"); }; get "/:user" => sub ($c) { my $user = $c.captured<user>; $c.render-json: { message => "hello $user!" }; }; app; $ crustup app.p6 http server is ready: http://127.0.0.1:5000/ minimal sinatra΋͋Δ
  5. ϦΞΫςΟϒ ϓϩάϥϛϯάͬͯʁ • ࢀߟURL • (A) ͳͥϦΞΫςΟϒϓϩάϥϛϯά͸ॏཁ͔ɻhttp://d.hatena.ne.jp/ pokarim/20101226 • (B)

    The introduction to Reactive Programming you've been missing https://gist.github.com/staltz/868e7e9bc2a7b8c1f754 • (C) What is (functional) reactive programming? http:// stackoverflow.com/questions/1028250/what-is-functional-reactive- programming • ͜ΕΒʹΑΔͱϦΞΫςΟϒϓϩάϥϛϯάͱ͸
 ࣌ؒͱͱ΋ʹมԽ͠͏Δ஋ = ࣌ؒॱʹฒΜͩΠϕϯτͷྻ = ετϦʔϜ
 Λத৺ʹͦ͑ͯϓϩάϥϛϯά͢Δ͜ͱɻ
  6. Perl6Ͱ͸ετϦʔϜ=Supply • Perl6Ͱ͸Supplyܕ͕ετϦʔϜʹରԠ͢Δ • ྫ • γάφϧ͸Supplyͱͯ͠ఏڙ͞ΕΔ • ֎෦ίϚϯυͷstdout/err͕Supplyͱͯ͠ఏڙ͞ΕΔ my

    $signal-supply = signal(SIGINT); say $signal-supply ~~ Supply; # True my $proc = Proc::Async.new("dstat"); say $proc.stdout ~~ Supply; # True
  7. Supplyৄࡉ - ࡞Γํ # ϑΝΠϧγεςϜͷมߋ௨஌Supply my $fs-supply = IO::Notification.watch-path(%*ENV<HOME>); #

    10ඵ͝ͱʹeventΛemit͢ΔSupply my $interval-supply = Supply.interval(10); # supplyϒϩοΫͰࣗ෼Ͱ࡞Δ͜ͱ΋Մೳ my $supply = supply { emit "value1"; sleep 1; emit "value2"; };
  8. Supplyৄࡉ - ૢ࡞ • ઌ΄ͲετϦʔϜͷૢ࡞ͱͯ͠filter, mapΛڍ͛ ͨɻPerl6ͩͱgrep, mapͰͰ͖Δɻ # dotfileΛൈ͍ͨSupply

    my $not-dotfiles = IO::Notification.watch-path(%*ENV<HOME>).grep: -> $e { $e.path.IO.basename !~~ /^'.'/; }; # 10ඵ͝ͱʹ࣌ࠁΛemit͢ΔSupply my $time-supply = Supply.interval(10).map({DateTime.now});
  9. ࣾ಺͔ΒͷΞΫηεΛআ͖ 1෼͝ͱʹrequest/secΛग़͢ -> ΋ͬͱ͍͍ॻ͖ํ͕͋Δ͸ͣ use IO::TailFile; my $count = 0;

    my $promise = Promise.new; my $tail = IO::TailFile.watch("access.log", :chomp) .grep(-> $line { $line !~~ / '192.168' / }) .map(-> $line { 1 }); $tail.tap: -> $i { $count += $i }, done => { $promise.keep(Nil) }; my $interval = Supply.interval(60); $interval.tap: -> $v { say "rps " ~ ($count / 60); $count = 0 }; await $promise;
  10. use v6; use IO::TailFile; my $tail = IO::TailFile.watch("access.log"); # infinite

    list! my @line = $tail.list.lazy; for @line -> $line { # ... } # react, whenever block! react { whenever $tail -> $line { # ... }; whenever Supply.ineterval(10) { # ... }; };
  11. ݁࿦ • ϦΞΫςΟϒϓϩάϥϛϯάͱ͸ετϦʔϜΛ த৺ͱͯ͠ϓϩάϥϛϯά͢Δख๏ • Perl6Ͱ͸ ετϦʔϜ = Supply •

    Supplyͷϝιου͸ͦΖ͓ͬͯΓ
 Perl6ͰϦΞΫςΟϒϓϩάϥϛϯά͍͚Δ!
 (ଟ෼)