Last active
July 16, 2019 18:02
-
-
Save marklemay/ca8775b8c728179eeaf1d5ce34d22fc5 to your computer and use it in GitHub Desktop.
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
# see http://math.andrej.com/2007/09/28/seemingly-impossible-functional-programs/ | |
def cons(head, tail): | |
def out(i): | |
if i == 0: | |
return head | |
else: | |
return tail(i - 1) | |
return out | |
all_ones = lambda _: 1 | |
all_zeros = lambda _: 0 | |
every_other = lambda i: i % 2 | |
def print_stream(f): | |
[print(f(x), end=", ") for x in range(10)] | |
print("...") | |
print_stream(all_ones) | |
print_stream(all_zeros) | |
print_stream(cons(1, all_zeros)) | |
print_stream(every_other) | |
def for_some(pred): | |
return pred(find(lambda a: pred(a))) | |
def find(pred): | |
def wrap(i): | |
# print(i) | |
if for_some(lambda a: pred(cons(0, a))): # needs to be lazy! | |
return cons(0, find(lambda a: pred(cons(0, a))))(i) | |
else: | |
return cons(1, find(lambda a: pred(cons(1, a))))(i) | |
return wrap | |
def for_every(pred): | |
return not for_some(lambda a: not pred(a)) | |
# print(for_every(lambda _: False)) | |
# print(for_every(lambda _: True)) | |
# print(for_every(lambda stream: stream(3) == 1)) | |
def equal(f, g): | |
return for_every(lambda a: f(a) == g(a)) | |
print(equal(lambda stream: stream(3) == 1, lambda stream: stream(3) == 1)) | |
# print(equal(lambda stream: stream(3) == 1, lambda stream: stream(4) == 1)) | |
# find(lambda _: False)(4) | |
# print_stream(find(lambda _: False)) | |
# print_stream(find(lambda _: True)) | |
# print_stream(find(lambda stream: stream(3) == 1)) | |
# # print_stream(find(lambda _: False)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment