Skip to content

Instantly share code, notes, and snippets.

@hastebrot
Last active December 17, 2016 17:23
Show Gist options
  • Select an option

  • Save hastebrot/ef392bf29a84e04ca98aea083fa60004 to your computer and use it in GitHub Desktop.

Select an option

Save hastebrot/ef392bf29a84e04ca98aea083fa60004 to your computer and use it in GitHub Desktop.
# side effects, mutable object, impure functions
sprites = ["inky", "blinky", "pinky", "clyde"]
print(sprites)
print(sprites.append("pacman"))
print(sprites)
print(sprites + ["pacman"])
print(sprites)
# OOP PYTHON.
len_sprites = []
for sprite in sprites:
len_sprite = len(sprite)
if (len_sprite >= 5):
len_sprites.append(len_sprite)
print(sprites)
print(len_sprites)
# FP PYTHON.
print(list(
filter(lambda it: it >= 5,
map(lambda it: len(it), sprites))))
print([len(it) for it in sprites if len(it) >= 5])
# LODASH PYTHON.
def chain(value): return ChainWrapper(value)
class ChainWrapper:
def __init__(self, value):
self._value = value
def __str__(self):
return "chain(" + str(self._value) + ")"
def map(self, func):
return ChainWrapper(map(func, self._value))
def filter(self, func):
return ChainWrapper(filter(func, self._value))
def value(self):
return list(self._value)
print(chain(sprites))
print(chain(sprites)
.value())
print(chain(sprites)
.map(lambda it: len(it))
.value())
print(chain(sprites)
.map(lambda it: len(it))
.filter(lambda it: it >= 5)
.value())
# LODASH/FP PYTHON.
# def plus(a, b): return a + b
# def plus_(a): return lambda b: a + b
def fp_map(func):
return lambda iterable: map(func, iterable)
def fp_filter(func):
return lambda iterable: filter(func, iterable)
print(list(
fp_filter(lambda it: it >= 5)(
fp_map(lambda it: len(it))(sprites))))
def pipe(value, *funcs):
for func in funcs:
value = func(value)
return value
print(pipe(
sprites,
fp_map(lambda it: len(it)),
fp_filter(lambda it: it >= 5),
list
))
# reducer.
# from functools import reduce
def reduce(func, values):
values = iter(values)
accum_value = next(values)
for value in values:
accum_value = func(accum_value, value)
return accum_value
print(reduce(lambda accum, value: value(accum), [
sprites,
lambda next: map(lambda it: len(it), next),
lambda next: filter(lambda it: it >= 5, next),
list
]))
def curry(func, first):
return lambda next: func(first, next)
def pipe(*funcs):
return reduce(lambda accum, value: value(accum), funcs)
print(pipe(
sprites,
curry(map, lambda it: len(it)),
curry(filter, lambda it: it >= 5),
list
))
def reduce_filter(func, values):
return reduce(lambda accum, value: accum + [value] if func(value) else accum,
[[]] + values)
print(reduce_filter(lambda it: len(it) >= 5, sprites))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment