bump version
[gitmo/Moose-Autobox.git] / lib / Moose / Autobox / Code.pm
CommitLineData
5f654d8e 1package Moose::Autobox::Code;
2use Moose::Role 'with';
7dad2765 3use Moose::Autobox;
5f654d8e 4
5efb6885 5our $VERSION = '0.14';
5f654d8e 6
7with 'Moose::Autobox::Ref';
8
9sub curry {
10 my ($f, @a) = @_;
11 return sub { $f->(@a, @_) }
12}
13
14sub rcurry {
15 my ($f, @a) = @_;
16 return sub { $f->(@_, @a) }
17}
18
19sub compose {
20 my ($f, $f2, @rest) = @_;
21 return $f if !$f2;
22 return (sub { $f2->($f->(@_)) })->compose(@rest);
23}
24
25sub disjoin {
26 my ($f, $f2) = @_;
27 return sub { $f->(@_) || $f2->(@_) }
28}
29
30sub conjoin {
31 my ($f, $f2) = @_;
32 return sub { $f->(@_) && $f2->(@_) }
33}
34
be334002 35# fixed point combinators
36
bb5a920e 37sub u {
38 my $f = shift;
39 sub { $f->($f, @_) };
40}
41
42sub y {
43 my $f = shift;
be334002 44 (sub { my $h = shift; sub { $f->(($h->u)->())->(@_) } }->u)->();
bb5a920e 45}
46
31d40d73 471;
48
49__END__
50
51=pod
52
53=head1 NAME
54
55Moose::Autobox::Code - the Code role
56
57=head1 SYNOPOSIS
58
59 use Moose::Autobox;
31d40d73 60
61 my $adder = sub { $_[0] + $_[1] };
5272f13f 62 my $add_2 = $adder->curry(2);
31d40d73 63
64 $add_2->(2); # returns 4
bb5a920e 65
66 # create a recursive subroutine
67 # using the Y combinator
68 *factorial = sub {
69 my $f = shift;
70 sub {
71 my $n = shift;
72 return 1 if $n < 2;
73 return $n * $f->($n - 1);
74 }
75 }->y;
76
77 factorial(10) # returns 3628800
78
31d40d73 79
80=head1 DESCRIPTION
81
8937074a 82This is a role to describe operations on the Code type.
83
260cc81f 84=head1 METHODS
85
86=over 4
87
5272f13f 88=item B<curry (@values)>
89
90=item B<rcurry (@values)>
91
92=item B<conjoin (\&sub)>
260cc81f 93
5272f13f 94=item B<disjoin (\&sub)>
260cc81f 95
5272f13f 96=item B<compose (@subs)>
260cc81f 97
5272f13f 98This will take a list of C<@subs> and compose them all into a single
99subroutine where the output of one sub will be the input of another.
260cc81f 100
bb5a920e 101=item B<y>
102
103This implements the Y combinator.
104
105=item B<u>
106
107This implements the U combinator.
108
5272f13f 109=back
110
111=over 4
260cc81f 112
5272f13f 113=item B<meta>
260cc81f 114
115=back
116
bb5a920e 117=head1 SEE ALSO
118
119=over 4
120
121=item L<http://en.wikipedia.org/wiki/Fixed_point_combinator>
122
be334002 123=item L<http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/20469>
124
bb5a920e 125=back
126
31d40d73 127=head1 BUGS
128
129All complex software has bugs lurking in it, and this module is no
130exception. If you find a bug please either email me, or add the bug
131to cpan-RT.
132
133=head1 AUTHOR
134
135Stevan Little E<lt>stevan@iinteractive.comE<gt>
136
137=head1 COPYRIGHT AND LICENSE
138
ea4e64bf 139Copyright 2006-2008 by Infinity Interactive, Inc.
31d40d73 140
141L<http://www.iinteractive.com>
142
143This library is free software; you can redistribute it and/or modify
144it under the same terms as Perl itself.
145
f6e003cc 146=cut