Created
July 6, 2017 15:30
-
-
Save afresh1/5b55f1f83e6475c33009eb18eed09929 to your computer and use it in GitHub Desktop.
A core perl port of https://aphyr.com/posts/340-acing-the-technical-interview
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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