tylerjw / fp

Functional Programming extensions to C++ for ROS projects.
https://www.fplib.dev
BSD 3-Clause "New" or "Revised" License
4 stars 4 forks source link

Currying template #7

Open tylerjw opened 2 years ago

tylerjw commented 2 years ago

Need

In order to call functions that have multiple inputs in a monadic way As a user I want to have nice syntax for curing a function

Scenario

Scenario: fp should provide a curry function GIVEN A function with multiple inputs WHEN I curry it with this new Curried type THEN I should have a function that can be called with a single argument.

Reference: https://en.wikipedia.org/wiki/Currying

Tasks

tylerjw commented 2 years ago

https://compiler-explorer.com/z/WYKMT4eY6

tylerjw commented 2 years ago

Pasting here incase the compiler-explorer link ever goes dead:

#include <iostream>

template <typename Callable, typename... Params>
auto curry(Callable f, Params... ps)
{
  if constexpr (requires { f(ps...); }) {
    return f(ps...);
  } else {
    return [f, ps...] (auto... qs)
    {
      return curry(f, ps..., qs...);
    };
  }
}

int func1(int x, int y)
{
  return x + y;
}

int main()
{
  const auto f = curry(func1);
  std::cout << f(1)(2) << '\n';
  return 0;
}
tylerjw commented 2 years ago

https://github.com/lefticus/tools/blob/main/include/lefticus/tools/curry.hpp