Last active
August 29, 2015 13:57
-
-
Save peczenyj/9445226 to your computer and use it in GitHub Desktop.
Monads in Perl, with operator >>= , is it possible?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package Maybe; | |
use Moo::Role; | |
has value => (is => 'ro', required => 1); | |
use overload | |
'>>='=> \&bind; | |
sub bind { | |
my ($self, $f) = @_; | |
$f->($self) | |
} | |
package Just; | |
use Moo; | |
with 'Maybe'; | |
use overload | |
'""' => \&str, | |
'+' => \∑ | |
sub str { | |
my ($self ) = @_; | |
"Just(". $self->value .")" | |
} | |
sub sum { | |
my ($self, $new_value) = @_; | |
$self->value + $new_value | |
} | |
package main; | |
my $a = Just->new(value => 1); | |
my $f = sub { | |
my ($self ) = @_; | |
Just->new(value => $self + 1) | |
}; | |
my $b = $a >>= $f; | |
print $b; # will print Just(2) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# using Attribute::Overload | |
package Maybe; | |
use Attribute::Overload; | |
use Moo::Role; | |
has value => (is => 'ro', required => 1); | |
sub bind :Overload(>>=) { | |
my ($self, $f) = @_; | |
$f->($self) | |
} | |
package Just; | |
use Moo; | |
with 'Maybe'; | |
sub str :Overload(""){ | |
my ($self ) = @_; | |
"Just(". $self->value .")" | |
} | |
sub sum :Overload(+){ | |
my ($self, $new_value) = @_; | |
$self->value + $new_value | |
} | |
package main; | |
my $a = Just->new(value => 1); | |
my $f = sub { | |
my ($self ) = @_; | |
Just->new(value => $self + 1) | |
}; | |
my $b = $a >>= $f; | |
print $b; # will print Just(2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Interesting. Have you seen https://github.com/robrwo/perl-monads or https://github.com/hiratara/p5-Data-Monad ?