Skip to content

Instantly share code, notes, and snippets.

@SilvaEmerson
Last active August 28, 2022 19:12
Show Gist options
  • Save SilvaEmerson/7659693d78031375b672a016d5d11595 to your computer and use it in GitHub Desktop.
Save SilvaEmerson/7659693d78031375b672a016d5d11595 to your computer and use it in GitHub Desktop.
Curry in Python
from inspect import signature
def get_params_len(fn): return len(signature(fn).parameters)
def curry(fn):
fn_params_len = get_params_len(fn)
temp_params = []
def _(*args):
if (len(args) + len(temp_params)) <= fn_params_len:
temp_params.append(*args)
if len(temp_params) == fn_params_len:
return fn(*temp_params)
return _
raise Exception('Number of arguments was too much')
return _

How this works

Using decorator(@) notation

from Curry import curry

@curry
def split_by(character, word):
    return word.split(character)

OR passing the function to be curried to curry function.

def split_by(character, word):
    return word.split(character)

split_by = curry(split_by)

When we use curry on a function, allow us to "consume" such function, bit by bit, also called partial application of the function. We don't need to pass all the parameter at once.

split_by_spaces = split_by(' ')
split_by_spaces('Hello my name is Emerson')
#['Hello', 'my', 'name', 'is', 'Emerson']

Como funciona

Usando decorator(@)

from Curry import curry

@curry
def split_by(character, word):
    return word.split(character)

OU passando a função que vai ser aplicado o curry, para a função curry.

def split_by(character, word):
    return word.split(character)

split_by = curry(split_by)

Quando usamos curry em uma função, nos permite "consumir" a mesma função pouco a pouco, também chamado de aplicação parcial da função. Nós não precisamos passar todos os parâmetros de uma vez.

split_by_spaces = split_by(' ')
split_by_spaces('Hello my name is Emerson')
#['Hello', 'my', 'name', 'is', 'Emerson']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment