Domanda

Che cos'è il curry?

Come si può fare il curry in C ++?

Spiegare i leganti nel contenitore STL?

È stato utile?

Soluzione

In breve, il curry accetta una funzione f(x, y) e, dato un Y fisso, fornisce una nuova funzione g(x) dove

g(x) == f(x, Y)

Questa nuova funzione può essere chiamata in situazioni in cui viene fornito un solo argomento e passa la chiamata alla funzione f originale con l'argomento <=> fisso.

I raccoglitori nell'STL consentono di farlo per le funzioni C ++. Ad esempio:

#include <functional>
#include <iostream>
#include <vector>

using namespace std;

// declare a binary function object
class adder: public binary_function<int, int, int> {
public:
    int operator()(int x, int y) const
    {
        return x + y;
    }
};

int main()
{
    // initialise some sample data
    vector<int> a, b;
    a.push_back(1);
    a.push_back(2);
    a.push_back(3);

    // here we declare a function object f and try it out
    adder f;
    cout << "f(2, 3) = " << f(2, 3) << endl;

    // transform() expects a function with one argument, so we use
    // bind2nd to make a new function based on f, that takes one
    // argument and adds 5 to it
    transform(a.begin(), a.end(), back_inserter(b), bind2nd(f, 5));

    // output b to see what we got
    cout << "b = [" << endl;
    for (vector<int>::iterator i = b.begin(); i != b.end(); ++i) {
        cout << "  " << *i << endl;
    }
    cout << "]" << endl;

    return 0;
}

Altri suggerimenti

1. Che cos'è il curry?

Currying significa semplicemente una trasformazione di una funzione di più argomenti in una funzione di un singolo argomento. Questo è più facilmente illustrato usando un esempio:

Accetta una funzione f che accetta tre argomenti:

int
f(int a,std::string b,float c)
{
    // do something with a, b, and c
    return 0;
}

Se vogliamo chiamare f(1,"some string",19.7f), dobbiamo fornire tutti i suoi argomenti curried_f=curry(f).

Quindi una versione al curry di a, chiamiamola curried_f(1)("some string")(19.7f) si aspetta solo un singolo argomento, che corrisponde al primo argomento di curried_f(1), vale a dire l'argomento curried_f. Inoltre, auto curried=curry(f)(arg1)(arg2)(arg3) può anche essere scritto usando la versione curry come auto result=curried(arg4)(arg5). Il valore di ritorno di _dtl::_curry d'altra parte è solo un'altra funzione, che gestisce l'argomento successivo di curry. Alla fine, finiamo con una funzione o richiamabile std::function che soddisfa la seguente uguaglianza:

curried_f(first_arg)(second_arg)...(last_arg) == f(first_arg,second_arg,...,last_arg).

2. Come si può ottenere il curry in C ++?

Quanto segue è un po 'più complicato, ma funziona molto bene per me (usando c ++ 11) ... Permette anche di curry di grado arbitrario in questo modo: FUNCTION e successivi fun. Ecco qui:

#include <functional>

namespace _dtl {

    template <typename FUNCTION> struct
    _curry;

    // specialization for functions with a single argument
    template <typename R,typename T> struct
    _curry<std::function<R(T)>> {
        using
        type = std::function<R(T)>;

        const type
        result;

        _curry(type fun) : result(fun) {}

    };

    // recursive specialization for functions with more arguments
    template <typename R,typename T,typename...Ts> struct
    _curry<std::function<R(T,Ts...)>> {
        using
        remaining_type = typename _curry<std::function<R(Ts...)> >::type;

        using
        type = std::function<remaining_type(T)>;

        const type
        result;

        _curry(std::function<R(T,Ts...)> fun)
        : result (
            [=](const T& t) {
                return _curry<std::function<R(Ts...)>>(
                    [=](const Ts&...ts){ 
                        return fun(t, ts...); 
                    }
                ).result;
            }
        ) {}
    };
}

template <typename R,typename...Ts> auto
curry(const std::function<R(Ts...)> fun)
-> typename _dtl::_curry<std::function<R(Ts...)>>::type
{
    return _dtl::_curry<std::function<R(Ts...)>>(fun).result;
}

template <typename R,typename...Ts> auto
curry(R(* const fun)(Ts...))
-> typename _dtl::_curry<std::function<R(Ts...)>>::type
{
    return _dtl::_curry<std::function<R(Ts...)>>(fun).result;
}

#include <iostream>

void 
f(std::string a,std::string b,std::string c)
{
    std::cout << a << b << c;
}

int 
main() {
    curry(f)("Hello ")("functional ")("world!");
    return 0;
}

Visualizza output

OK, come ha commentato Samer, dovrei aggiungere alcune spiegazioni su come funziona. L'implementazione effettiva viene eseguita in N-1, mentre le funzioni del modello _curry<Ts...> sono solo wrapper di convenienza. L'implementazione è ricorsiva rispetto agli argomenti dell'argomento if constexpr argomento del modello void_t.

Per una funzione con un solo argomento, il risultato è identico alla funzione originale.

        _curry(std::function<R(T,Ts...)> fun)
        : result (
            [=](const T& t) {
                return _curry<std::function<R(Ts...)>>(
                    [=](const Ts&...ts){ 
                        return fun(t, ts...); 
                    }
                ).result;
            }
        ) {}

Qui la cosa complicata: per una funzione con più argomenti, restituiamo un lambda il cui argomento è associato al primo argomento della chiamata a constexpr if. Infine, il curry rimanente per gli altri needs_unapply<decltype(f)>::value argomenti viene delegato all'implementazione di <=> con un argomento modello in meno.

Aggiornamento per c ++ 14/17:

Mi è appena venuta in mente una nuova idea per affrontare il problema del curry ... Con l'introduzione di <=> in c ++ 17 (e con l'aiuto di <=> per determinare se una funzione è completamente curry), le cose sembrano diventare molto più facili:

template< class, class = std::void_t<> > struct 
needs_unapply : std::true_type { };

template< class T > struct 
needs_unapply<T, std::void_t<decltype(std::declval<T>()())>> : std::false_type { };

template <typename F> auto
curry(F&& f) {
  /// Check if f() is a valid function call. If not we need 
  /// to curry at least one argument:
  if constexpr (needs_unapply<decltype(f)>::value) {
       return [=](auto&& x) {
            return curry(
                [=](auto&&...xs) -> decltype(f(x,xs...)) {
                    return f(x,xs...);
                }
            );
        };    
  }
  else {  
    /// If 'f()' is a valid call, just call it, we are done.
    return f();
  }
}

int 
main()
{
  auto f = [](auto a, auto b, auto c, auto d) {
    return a  * b * c * d;
  };

  return curry(f)(1)(2)(3)(4);
}

Guarda il codice in azione su qui . Con un approccio simile, qui è come valutare le funzioni con un numero arbitrario di argomenti.

La stessa idea sembra funzionare anche in C ++ 14, se scambiamo <=> con una selezione di modello a seconda del test <=>:

template <typename F> auto
curry(F&& f);

template <bool> struct
curry_on;

template <> struct
curry_on<false> {
    template <typename F> static auto
    apply(F&& f) {
        return f();
    }
};

template <> struct
curry_on<true> {
    template <typename F> static auto 
    apply(F&& f) {
        return [=](auto&& x) {
            return curry(
                [=](auto&&...xs) -> decltype(f(x,xs...)) {
                    return f(x,xs...);
                }
            );
        };
    }
};

template <typename F> auto
curry(F&& f) {
    return curry_on<needs_unapply<decltype(f)>::value>::template apply(f);
}

Semplificando l'esempio di Gregg, usando tr1:

#include <functional> 
using namespace std;
using namespace std::tr1;
using namespace std::tr1::placeholders;

int f(int, int);
..
int main(){
    function<int(int)> g     = bind(f, _1, 5); // g(x) == f(x, 5)
    function<int(int)> h     = bind(f, 2, _1); // h(x) == f(2, x)
    function<int(int,int)> j = bind(g, _2);    // j(x,y) == g(y)
}

I componenti funzionali Tr1 ti consentono di scrivere codice ricco in stile funzionale in C ++. Inoltre, C ++ 0x consentirà anche alle funzioni lambda in linea di fare questo:

int f(int, int);
..
int main(){
    auto g = [](int x){ return f(x,5); };      // g(x) == f(x, 5)
    auto h = [](int x){ return f(2,x); };      // h(x) == f(2, x)
    auto j = [](int x, int y){ return g(y); }; // j(x,y) == g(y)
}

E mentre C ++ non fornisce la ricca analisi degli effetti collaterali eseguita da alcuni linguaggi di programmazione orientati al funzionamento, l'analisi const e la sintassi lambda C ++ 0x possono aiutare:

struct foo{
    int x;
    int operator()(int y) const {
        x = 42; // error!  const function can't modify members
    }
};
..
int main(){
    int x;
    auto f = [](int y){ x = 42; }; // error! lambdas don't capture by default.
}

Spero che sia d'aiuto.

Dai un'occhiata a Boost.Bind che rende il processo mostrato da Greg più versatile:

transform(a.begin(), a.end(), back_inserter(b), bind(f, _1, 5));

Questo collega 5 al secondo argomento di f.

È & # 8217; vale la pena notare che questo non è non curry (invece, è & # 8217; l'applicazione parziale). Tuttavia, l'utilizzo del curry in generale è difficile in C ++ (in effetti, solo di recente è diventato possibile) e al suo posto viene spesso utilizzata un'applicazione parziale.

Altre risposte spiegano bene i raccoglitori, quindi non ripeterò quella parte qui. Dimostrerò solo come si può fare curry e un'applicazione parziale con lambda in C ++ 0x.

Esempio di codice: (spiegazione nei commenti)

#include <iostream>
#include <functional>

using namespace std;

const function<int(int, int)> & simple_add = 
  [](int a, int b) -> int {
    return a + b;
  };

const function<function<int(int)>(int)> & curried_add = 
  [](int a) -> function<int(int)> {
    return [a](int b) -> int {
      return a + b;
    };
  };

int main() {
  // Demonstrating simple_add
  cout << simple_add(4, 5) << endl; // prints 9

  // Demonstrating curried_add
  cout << curried_add(4)(5) << endl; // prints 9

  // Create a partially applied function from curried_add
  const auto & add_4 = curried_add(4);
  cout << add_4(5) << endl; // prints 9
}

Se usi C ++ 14 è molto semplice:

template<typename Function, typename... Arguments>
auto curry(Function function, Arguments... args) {
    return [=](auto... rest) {
        return function(args..., rest...);
    }
}

Puoi quindi usarlo in questo modo:

auto add = [](auto x, auto y) { return x + y; }

// curry 4 into add
auto add4 = curry(add, 4);

add4(6); // 10

Currying è un modo per ridurre una funzione che accetta più argomenti in una sequenza di funzioni nidificate con un argomento ciascuno:

full = (lambda a, b, c: (a + b + c))
print full (1, 2, 3) # print 6

# Curried style
curried = (lambda a: (lambda b: (lambda c: (a + b + c))))
print curried (1)(2)(3) # print 6

Currying è bello perché puoi definire funzioni che sono semplicemente avvolgenti attorno ad altre funzioni con valori predefiniti, e quindi passare attorno alle funzioni semplificate. I raccoglitori C ++ STL forniscono un'implementazione di questo in C ++.

Alcune grandi risposte qui. Ho pensato di aggiungere il mio perché era divertente giocare con il concetto.

Applicazione con funzione parziale : il processo di " associazione " una funzione con solo alcuni dei suoi parametri, rinviando il resto da compilare in seguito. Il risultato è un'altra funzione con meno parametri.

Currying : è una forma speciale di applicazione con funzioni parziali in cui puoi solo " associare " un singolo argomento alla volta. Il risultato è un'altra funzione con esattamente 1 parametro in meno.

Il codice che sto per presentare è applicazione con funzione parziale da cui è possibile il curry, ma non l'unica possibilità. Offre alcuni vantaggi rispetto alle implementazioni di curry di cui sopra (principalmente perché è un'applicazione con funzione parziale e non curry, eh).

  • Applicazione su una funzione vuota:

    auto sum0 = [](){return 0;};
    std::cout << partial_apply(sum0)() << std::endl;
    
  • Applicazione di più argomenti alla volta:

    auto sum10 = [](int a, int b, int c, int d, int e, int f, int g, int h, int i, int j){return a+b+c+d+e+f+g+h+i+j;};
    std::cout << partial_apply(sum10)(1)(1,1)(1,1,1)(1,1,1,1) << std::endl; // 10
    
  • constexpr supporto che consente il tempo di compilazione static_assert:

    static_assert(partial_apply(sum0)() == 0);
    
  • Un utile messaggio di errore se accidentalmente si spinge troppo oltre nel fornire argomenti:

    auto sum1 = [](int x){ return x;};
    partial_apply(sum1)(1)(1);
    
      

    errore: static_assert non riuscito " Tentativo di applicare troppi argomenti! "

Altre risposte sopra restituiscono lambda che associano un argomento e quindi restituiscono ulteriori lambda. Questo approccio racchiude questa funzionalità essenziale in un oggetto richiamabile. Le definizioni per operator() consentono di chiamare il lambda interno. I modelli variabili ci consentono di verificare se qualcuno si spinge troppo oltre e una funzione di conversione implicita nel tipo di risultato della chiamata di funzione ci consente di stampare il risultato o confrontare l'oggetto con una primitiva.

Codice:

namespace detail{
template<class F>
using is_zero_callable = decltype(std::declval<F>()());

template<class F>
constexpr bool is_zero_callable_v = std::experimental::is_detected_v<is_zero_callable, F>;
}

template<class F>
struct partial_apply_t
{
    template<class... Args>
    constexpr auto operator()(Args... args)
    {
        static_assert(sizeof...(args) == 0 || !is_zero_callable, "Attempting to apply too many arguments!");
        auto bind_some = [=](auto... rest) -> decltype(myFun(args..., rest...))
        {
           return myFun(args..., rest...);
        };
        using bind_t = decltype(bind_some);

        return partial_apply_t<bind_t>{bind_some};
    }
    explicit constexpr partial_apply_t(F fun) : myFun(fun){}

    constexpr operator auto()
    {
        if constexpr (is_zero_callable)
            return myFun();
        else
            return *this; // a callable
    }
    static constexpr bool is_zero_callable = detail::is_zero_callable_v<F>;
    F myFun;
};

Demo live

Altre note:

  • Ho scelto di utilizzare is_detected principalmente per divertimento e pratica; serve come un carattere normale qui.
  • Potrebbe esserci sicuramente più lavoro fatto per supportare il perfetto inoltro per motivi di prestazioni
  • Il codice è C ++ 17 perché richiede <=> supporto lambda in C ++ 17
    • E sembra che GCC 7.0.1 non sia ancora del tutto lì, quindi ho usato Clang 5.0.0

Alcuni test:

auto sum0 = [](){return 0;};
auto sum1 = [](int x){ return x;};
auto sum2 = [](int x, int y){ return x + y;};
auto sum3 = [](int x, int y, int z){ return x + y + z; };
auto sum10 = [](int a, int b, int c, int d, int e, int f, int g, int h, int i, int j){return a+b+c+d+e+f+g+h+i+j;};

std::cout << partial_apply(sum0)() << std::endl; //0
static_assert(partial_apply(sum0)() == 0, "sum0 should return 0");
std::cout << partial_apply(sum1)(1) << std::endl; // 1
std::cout << partial_apply(sum2)(1)(1) << std::endl; // 2
std::cout << partial_apply(sum3)(1)(1)(1) << std::endl; // 3
static_assert(partial_apply(sum3)(1)(1)(1) == 3, "sum3 should return 3");
std::cout << partial_apply(sum10)(1)(1,1)(1,1,1)(1,1,1,1) << std::endl; // 10
//partial_apply(sum1)(1)(1); // fails static assert
auto partiallyApplied = partial_apply(sum3)(1)(1);
std::function<int(int)> finish_applying = partiallyApplied;
std::cout << std::boolalpha << (finish_applying(1) == 3) << std::endl; // true

auto plus2 = partial_apply(sum3)(1)(1);
std::cout << std::boolalpha << (plus2(1) == 3) << std::endl; // true
std::cout << std::boolalpha << (plus2(3) == 5) << std::endl; // true

Ho implementato anche il curry con modelli variadici (vedi la risposta di Julian). Tuttavia, non ho fatto uso della ricorsione o std::function. Nota: utilizza una serie di C ++ 14 .

L'esempio fornito (main funzione) viene effettivamente eseguito al momento della compilazione, dimostrando che il metodo di curring non supera le ottimizzazioni essenziali da parte del compilatore.

Il codice è disponibile qui: https://gist.github.com/Garciat/c7e4bef299ee5c607948

con questo file di supporto: https://gist.github.com/Garciat/cafe27d04cfdff0e891e

Il codice ha ancora bisogno di (molto) lavoro, che potrei o non potrei completare presto. Ad ogni modo, sto pubblicando questo qui per riferimento futuro.

Pubblicazione del codice in caso di interruzione dei collegamenti (sebbene non dovrebbero):

#include <type_traits>
#include <tuple>
#include <functional>
#include <iostream>

// ---

template <typename FType>
struct function_traits;

template <typename RType, typename... ArgTypes>
struct function_traits<RType(ArgTypes...)> {
    using arity = std::integral_constant<size_t, sizeof...(ArgTypes)>;

    using result_type = RType;

    template <size_t Index>
    using arg_type = typename std::tuple_element<Index, std::tuple<ArgTypes...>>::type;
};

// ---

namespace details {
    template <typename T>
    struct function_type_impl
      : function_type_impl<decltype(&T::operator())>
    { };

    template <typename RType, typename... ArgTypes>
    struct function_type_impl<RType(ArgTypes...)> {
        using type = RType(ArgTypes...);
    };

    template <typename RType, typename... ArgTypes>
    struct function_type_impl<RType(*)(ArgTypes...)> {
        using type = RType(ArgTypes...);
    };

    template <typename RType, typename... ArgTypes>
    struct function_type_impl<std::function<RType(ArgTypes...)>> {
        using type = RType(ArgTypes...);
    };

    template <typename T, typename RType, typename... ArgTypes>
    struct function_type_impl<RType(T::*)(ArgTypes...)> {
        using type = RType(ArgTypes...);
    };

    template <typename T, typename RType, typename... ArgTypes>
    struct function_type_impl<RType(T::*)(ArgTypes...) const> {
        using type = RType(ArgTypes...);
    };
}

template <typename T>
struct function_type
  : details::function_type_impl<typename std::remove_cv<typename std::remove_reference<T>::type>::type>
{ };

// ---

template <typename Args, typename Params>
struct apply_args;

template <typename HeadArgs, typename... Args, typename HeadParams, typename... Params>
struct apply_args<std::tuple<HeadArgs, Args...>, std::tuple<HeadParams, Params...>>
  : std::enable_if<
        std::is_constructible<HeadParams, HeadArgs>::value,
        apply_args<std::tuple<Args...>, std::tuple<Params...>>
    >::type
{ };

template <typename... Params>
struct apply_args<std::tuple<>, std::tuple<Params...>> {
    using type = std::tuple<Params...>;
};

// ---

template <typename TupleType>
struct is_empty_tuple : std::false_type { };

template <>
struct is_empty_tuple<std::tuple<>> : std::true_type { };

// ----

template <typename FType, typename GivenArgs, typename RestArgs>
struct currying;

template <typename FType, typename... GivenArgs, typename... RestArgs>
struct currying<FType, std::tuple<GivenArgs...>, std::tuple<RestArgs...>> {
    std::tuple<GivenArgs...> given_args;

    FType func;

    template <typename Func, typename... GivenArgsReal>
    constexpr
    currying(Func&& func, GivenArgsReal&&... args) :
      given_args(std::forward<GivenArgsReal>(args)...),
      func(std::move(func))
    { }

    template <typename... Args>
    constexpr
    auto operator() (Args&&... args) const& {
        using ParamsTuple = std::tuple<RestArgs...>;
        using ArgsTuple = std::tuple<Args...>;

        using RestArgsPrime = typename apply_args<ArgsTuple, ParamsTuple>::type;

        using CanExecute = is_empty_tuple<RestArgsPrime>;

        return apply(CanExecute{}, std::make_index_sequence<sizeof...(GivenArgs)>{}, std::forward<Args>(args)...);
    }

    template <typename... Args>
    constexpr
    auto operator() (Args&&... args) && {
        using ParamsTuple = std::tuple<RestArgs...>;
        using ArgsTuple = std::tuple<Args...>;

        using RestArgsPrime = typename apply_args<ArgsTuple, ParamsTuple>::type;

        using CanExecute = is_empty_tuple<RestArgsPrime>;

        return std::move(*this).apply(CanExecute{}, std::make_index_sequence<sizeof...(GivenArgs)>{}, std::forward<Args>(args)...);
    }

private:
    template <typename... Args, size_t... Indices>
    constexpr
    auto apply(std::false_type, std::index_sequence<Indices...>, Args&&... args) const& {
        using ParamsTuple = std::tuple<RestArgs...>;
        using ArgsTuple = std::tuple<Args...>;

        using RestArgsPrime = typename apply_args<ArgsTuple, ParamsTuple>::type;

        using CurryType = currying<FType, std::tuple<GivenArgs..., Args...>, RestArgsPrime>;

        return CurryType{ func, std::get<Indices>(given_args)..., std::forward<Args>(args)... };
    }

    template <typename... Args, size_t... Indices>
    constexpr
    auto apply(std::false_type, std::index_sequence<Indices...>, Args&&... args) && {
        using ParamsTuple = std::tuple<RestArgs...>;
        using ArgsTuple = std::tuple<Args...>;

        using RestArgsPrime = typename apply_args<ArgsTuple, ParamsTuple>::type;

        using CurryType = currying<FType, std::tuple<GivenArgs..., Args...>, RestArgsPrime>;

        return CurryType{ std::move(func), std::get<Indices>(std::move(given_args))..., std::forward<Args>(args)... };
    }

    template <typename... Args, size_t... Indices>
    constexpr
    auto apply(std::true_type, std::index_sequence<Indices...>, Args&&... args) const& {
        return func(std::get<Indices>(given_args)..., std::forward<Args>(args)...);
    }

    template <typename... Args, size_t... Indices>
    constexpr
    auto apply(std::true_type, std::index_sequence<Indices...>, Args&&... args) && {
        return func(std::get<Indices>(std::move(given_args))..., std::forward<Args>(args)...);
    }
};

// ---

template <typename FType, size_t... Indices>
constexpr
auto curry(FType&& func, std::index_sequence<Indices...>) {
    using RealFType = typename function_type<FType>::type;
    using FTypeTraits = function_traits<RealFType>;

    using CurryType = currying<FType, std::tuple<>, std::tuple<typename FTypeTraits::template arg_type<Indices>...>>;

    return CurryType{ std::move(func) };
}

template <typename FType>
constexpr
auto curry(FType&& func) {
    using RealFType = typename function_type<FType>::type;
    using FTypeArity = typename function_traits<RealFType>::arity;

    return curry(std::move(func), std::make_index_sequence<FTypeArity::value>{});
}

// ---

int main() {
    auto add = curry([](int a, int b) { return a + b; });

    std::cout << add(5)(10) << std::endl;
}

Questi collegamenti sono rilevanti:

La pagina Lambda Calculus su Wikipedia contiene un chiaro esempio di curry
http://en.wikipedia.org/wiki/Lambda_calculus#Motivation

Questo documento tratta il curry in C / C ++
http://asg.unige.ch/site/papers/Dami91a.pdf

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top