Skip to content

Instantly share code, notes, and snippets.

@peczenyj
Last active August 29, 2015 13:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peczenyj/9445226 to your computer and use it in GitHub Desktop.
Save peczenyj/9445226 to your computer and use it in GitHub Desktop.
Monads in Perl, with operator >>= , is it possible?
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)
# 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)
@robrwo
Copy link

robrwo commented Mar 10, 2014

@peczenyj
Copy link
Author

yes @robrwo but my focus was on the >>= operator, to mimic the Haskell >>=

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment