Created
November 21, 2015 11:40
-
-
Save Willyfrog/0a9794974e8cfb1dc2be to your computer and use it in GitHub Desktop.
introduccion al python funcional
This file contains 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
def trampolin(fun, *args, **kwargs): | |
result = [fun, args, kwargs] | |
while es_fun(result): | |
(fn, fun_args) = (result[0], result[1]) | |
if (len(result) == 3): | |
fun_kwargs = result[2] | |
else: | |
fun_kwargs = {} | |
result = fn(*fun_args, **fun_kwargs) | |
return result | |
def es_fun(lista): | |
try: | |
return callable(lista[0]) | |
except: | |
return False | |
def cuenta(num): | |
return cuenta(num-1) if num > 0 else "This is the end" | |
def cuenta_t(num): | |
return [cuenta_t, [num-1]] if num > 0 else "This is the end" | |
def compose_fn(f1, f2): | |
return lambda x: f1(f2(x)) | |
asegura_impar = compose_fn( | |
lambda x: x + 1, | |
lambda x: x * 2 | |
) | |
if __name__ == '__main__': | |
print trampolin(cuenta_t, 1000000) | |
# print cuenta(1000000) | |
print asegura_impar(3) |
This file contains 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
def reducir(funcion, secuencia, inicial=None): | |
if not secuencia: | |
return inicial | |
valor = secuencia.pop() | |
return reducir(funcion, secuencia, funcion(inicial, valor)) | |
def filtrar(filtro, secuencia): | |
parcial = anade_si(filtro) | |
return reducir(parcial, secuencia, []) | |
def anade_si(filtro): | |
return lambda acc, valor: [valor] + acc if filtro(valor) else acc | |
def mapear(funcion, secuencia): | |
parcial = aplica_une(funcion) | |
return reducir(parcial, secuencia, []) | |
def aplica_une(funcion): | |
return lambda acc, valor: [funcion(valor)] + acc | |
print mapear( | |
lambda x: x * 2, | |
filtrar(lambda y: y % 2, | |
range(1, 5)) | |
) | |
x2 = lambda x: x * 2 | |
impar = lambda y: y % 2 | |
print mapear( | |
x2, | |
filtrar(impar, range(1, 5)) | |
) | |
filtra_impares = lambda r: filtrar(impar, r) | |
print mapear(x2, filtra_impares(range(1, 5))) | |
dobla_impares = lambda sec: mapear(x2, filtra_impares(sec)) | |
print dobla_impares(range(1, 5)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment