Skip to content

Instantly share code, notes, and snippets.

@marcoonroad
Last active August 29, 2015 14:11
Show Gist options
  • Save marcoonroad/2776aa2f8ec4fbc21f0f to your computer and use it in GitHub Desktop.
Save marcoonroad/2776aa2f8ec4fbc21f0f to your computer and use it in GitHub Desktop.
Small OOP ideas based on / for Perl 5.
# ...
### gather / take ###
gather {
@xs -> for { | $x | ($x + 1) -> take }
} -> eval -> say;
# or
{
{ | $x | take $x + 1 } -> for @xs
} -> gather -> eval -> say;
# or
say gather (\&some-subroutine) -> eval;
# or
say eval gather \&another-subroutine;
# or
(\&any-block) -> gather -> eval -> say;
### given / when ###
$expr -> given
-> when { | 1 | "1" }
-> when { | any 2 ... 10 | "Between 2 and 10." }
-> default { "Lesser than 1 or greater than 10" }
-> eval -> say;
my $e = given $expr;
$e -> when { | 1 | say "1" };
$e -> when (\&some-block);
$e -> default { say "Lesser than 1 or greater than 10" };
$e -> eval;
### if / else ###
($x > 5) -> if
-> then { "Greater than 5." }
-> else { "Lesser or equal than 5." }
-> eval -> say;
# or
if ($x > 5)
-> then { say "Greater than 5." }
-> else { say "Lesser or equal than 5." }
-> eval;
# or
my $t = unless ($x <= 5);
$t -> then (\&any-block);
$t -> else { say "Lesser or equal than 5." };
$t -> eval;
### try / catch / finally ###
{ 5 / 0 } -> try
-> catch { | Unknown $e | "Was thrown an unknown error." -> say }
-> catch { | DivisionByZero $e | "Caught: $e..." -> say }
-> finally { "Exiting from exception test..." }
-> eval;
# or
my $x = try { 5 / 0 };
$x -> catch { | Unknown $e |
"Was thrown an unknown error." -> say
};
$x -> catch { | DivisionByZero $e |
"Caught: $e..." -> say
};
$x -> finally { "Exiting from exception test..." };
$x -> eval;
### map / reduce / grep ###
{ | $x | $x + 1 } -> map (1 ... 3) -> say;
# or
(1 ... 3) -> map { | $x | $x + 1 } -> say;
{ | $x | $x % 2 == 0 } -> grep (5 ... 15) -> say;
# or
(5 ... 15) -> grep { | $x | $x % 2 == 0 } -> say;
{ | $x, $y | $x + $y } -> reduce (1 ... 10) -> say;
# or
(1 ... 10) -> reduce { | $x, $y | $x + $y } -> say;
### assume / compose / call ###
my $add = { | $x, $y | $x + $y };
my $incr = $add -> assume (1);
say $incr -> call (9); # 10
my $square = { | $x | $x * $x };
my $stuff = $incr -> compose ($square, { | $x | $x + 2 }, $incr);
$stuff -> call (4) -> say; # 28
# 4 + 1 => 5 | 5 * 5 => 25 | 25 + 2 => 27 | 27 + 1 => 28
### call/cc ###
my $backup;
say 5 + call-cc { | $e |
$backup = $e;
8;
}; # 13
say $backup -> call (12); # 5 + 12 => 17
### coro / yield / from ###
my $c = { | @xs | @xs -> for { | $x | $x -> yield } }
-> coro; # returns a coroutine constructor
$c -> play (1 ... 3) # make an instance + returns a generator
-> from # cast generator to a lazy list (eval-by-need)
-> for { | $y | say $y };
### end of script ###
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment