Skip to content

Instantly share code, notes, and snippets.

@afresh1
Created July 6, 2017 15:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afresh1/5b55f1f83e6475c33009eb18eed09929 to your computer and use it in GitHub Desktop.
Save afresh1/5b55f1f83e6475c33009eb18eed09929 to your computer and use it in GitHub Desktop.
use v5.24.0;
use warnings;
use feature 'signatures';
no warnings 'experimental::signatures';
# https://aphyr.com/posts/340-acing-the-technical-interview
sub true() { 1 }
sub false() { 0 }
sub cons($h, $t) {
sub ($x) { $x ? $h : $t }
}
{
my $x = cons 1, cons 2, undef;
say $x->(true);
# 1
say $x->(false)->(true);
# 2
say $x;
# CODE(0x947a5f8)
}
sub nth($l, $n) {
$l and
$n == 0
? $l->(true)
: __SUB__->($l->(false), $n - 1)
}
sub prn_list($l) {
print "(";
sub ($l) {
!defined $l
? print ")\n"
: do {
print $l->(true);
print " " if $l->(false);
__SUB__->($l->(false))
}
}->($l)
}
prn_list cons 1, cons 2, cons 3, undef;
# (1 2 3)
sub reversed($l) {
sub ($r, $l) {
$l
? __SUB__->(cons($l->(true), $r), $l->(false))
: $r
}->(undef, $l)
}
prn_list reversed cons 1, cons 2, cons 3, undef;
# (3 2 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment