-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOption.pm
More file actions
70 lines (55 loc) · 1012 Bytes
/
Copy pathOption.pm
File metadata and controls
70 lines (55 loc) · 1012 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package Option;
use Exporter 'import';
@EXPORT_OK = qw(None Some Option);
use strict;
use warnings;
sub None {
return Option->new;
};
sub Some {
return Option->new(@_);
};
sub new {
my ($class, $arg) = @_;
if (defined $arg) {
return bless { value => $arg }, $class;
} else {
return bless { value => undef }, $class;
}
};
sub some {
return defined $_[0]->{value};
}
sub eql {
my ($self, $that) = @_;
return $that->{value} == $self->{value};
}
sub stringify {
my ($self) = @_;
return $self->map(sub { return "Some($_[0])"; })->getOrElse("None");
}
sub map {
my ($self, $fn) = @_;
if ($self->some) {
return Option->new($fn->($self->{value}));
} else {
return $self;
}
}
sub fold {
my ($self, $a, $b) = @_;
if (not $self->some) {
return Option->new($a->());
} else {
return Option->new($b->($self->{value}));
}
}
sub getOrElse {
my ($self, $alt) = @_;
if ($self->some) {
return $self->{value};
} else {
return $alt;
}
}
1;