草庐IT

c++ - C++ 中的 Monad 接口(interface)

coder 2023-06-02 原文

我目前正在学习一点点 Haskell 并开始弄清楚 monad 是如何工作的。
由于我通常编写 C++ 代码,并且我认为 monad 模式(正如我现在所理解的那样)在 C++ 中使用也非常棒,例如用于 future 等,

我想知道是否有一种方法可以实现接口(interface)或基类来强制正确重载函数 bindreturn (原因与 C++ 的 return 不同)用于派生类型?

为了更清楚地说明我在想什么:

考虑我们有以下非成员函数:

auto foo(const int x) const -> std::string;

还有一个成员函数bar对于不同的类有不同的重载:
auto bar() const -> const *Monad<int>;

如果我们现在想做这样的事情: foo(someMember.bar()) ,
这根本行不通。因此,如果必须知道返回什么 bar,例如它是否返回 future<int> ,我们要拨打bar().get() , 哪些会阻塞,即使我们不需要在这里阻塞。

在haskell中,我们可以做类似bar >>= foo的事情。

所以我问自己我们是否可以在 C++ 中实现这样的行为,因为在调用 foo(x) 时我们不在乎 x 是否是一个将 int 装箱的对象,以及在什么样的类(class)int已装箱,我们只想应用函数 foo在盒装类型上。

很抱歉我在用英语表达我的想法时遇到了一些问题,因为我不是母语人士。

最佳答案

首先请注意,作为 monad 不是类型的属性,而是类型构造函数的属性。

例如。在 Haskell 中,您将拥有 List a作为类型和 List作为类型构造函数。在 C++ 中,我们对模板具有相同的功能:std::list是一个类型构造函数,可以构造类型 std::list<int> .这里List是一个 monad,但是 List Bool不是。

为了类型构造函数 M要成为 monadic,它需要提供两个特殊功能:

  • 提升某种类型的任意值的函数 T到 monad,即 T -> M<T> 类型的函数.这个函数叫做return在 haskell 。
  • 类型为 bind 的函数(在 Haskell 中称为 M<T> ->(T -> M<T'>) -> M<T'>) ,即接受类型为 M<T> 的对象的函数和类型为 T -> M<T'> 的函数并将参数函数应用于 T包裹在参数中的对象 M<T> .

  • 这两个函数也有一些属性必须满足,但由于语义属性不能在编译时检查(无论是在 Haskell 中还是在 C++ 中),我们在这里真的不需要关心它们。

    然而,一旦我们决定了它们的语法/名称,我们可以检查的是这两个函数的存在和类型。
    对于第一个,明显的选择是一个构造函数,它只接受任何给定类型的一个元素 T .对于第二个,我决定使用 operator>>=因为我希望它是一个操作符以避免嵌套函数调用并且它类似于 Haskell 表示法(但不幸的是它是右结合的 - 哦,好吧)。

    检查 monadic 接口(interface)

    那么如何检查模板的属性呢?幸运的是,C++ 中有模板-模板参数和 SFINAE。

    首先,我们需要一种方法来确定是否确实存在一个接受任意类型的构造函数。我们可以通过检查给定类型构造函数 M 来近似它。型号 M<DummyType>对于虚拟类型,格式良好 struct DummyType{};我们定义。通过这种方式,我们可以确保我们正在检查的类型不会有专门化。

    对于 bind我们做同样的事情:检查是否有 operator>>=(M<DummyType> const&, M<DummyType2>(*)(DummyType))并且返回的类型实际上是 M<DummyType2> .

    可以使用 C++17s 来检查函数是否存在 std::void_t (我强烈推荐 Walter Browns 在 CppCon 2014 上的演讲,他介绍了该技术)。可以使用 std::is_same 来检查类型是否正确。

    总之,这看起来像这样:
    // declare the two dummy types we need for detecting constructor and bind
    struct DummyType{};
    struct DummyType2{};
    
    // returns the return type of the constructor call with a single 
    // object of type T if such a constructor exists and nothing 
    // otherwise. Here `Monad` is a fixed type constructor.
    template <template<typename, typename...> class Monad, typename T>
    using constructor_return_t
        = decltype(Monad<T>{std::declval<T>()});
    
    // returns the return type of operator>>=(const Monad<T>&, Monad<T'>(*)(T))
    // if such an operator is defined and nothing otherwise. Here Monad 
    // is a fixed type constructor and T and funcType are arbitrary types.
    template <template <typename, typename...> class Monad, typename T, typename T'>
    using monadic_bind_t
        = decltype(std::declval<Monad<T> const&>() >>= std::declval<Monad<T'>(*)(T)>());
    
    // logical 'and' for std::true_type and it's children
    template <typename, typename, typename = void>
    struct type_and : std::false_type{};
    template<typename T, typename T2>
    struct type_and<T, T2, std::enable_if_t<std::is_base_of<std::true_type, T>::value && std::is_base_of<std::true_type, T2>::value>> 
        : std::true_type{};
    
    
    // the actual check that our type constructor indeed satisfies our concept
    template <template <typename, typename...> class, typename = void>
    struct is_monad : std::false_type {};
    
    template <template <typename, typename...> class Monad>
    struct is_monad<Monad, 
                    void_t<constructor_return_t<Monad, DummyType>,
                           monadic_bind_t<Monad, DummyType, DummyType2>>>
        : type_and<std::is_same<monadic_bind_t<Monad, DummyType, DummyType2>,
                                Monad<DummyType2>>,
                   std::is_same<constructor_return_t<Monad, DummyType>,
                                Monad<DummyType>>> {};
    

    请注意,即使我们通常希望类型构造函数采用单个类型 T作为参数,我使用了可变参数模板模板参数来说明通常在 STL 容器中使用的默认分配器。没有它,你就无法制作 std::vector上面定义的概念意义上的单子(monad)。

    使用类型特征实现基于 monadic 接口(interface)的泛型函数

    monads 的一大优势是,只有 monadic 接口(interface)可以做很多事情。例如我们知道每个 monad 也是一个 applicative,所以我们可以写 Haskell 的 ap函数并用它来实现liftM这允许将任何普通函数应用于一元值。
    // ap
    template <template <typename, typename...> class Monad, typename T, typename funcType>
    auto ap(const Monad<funcType>& wrappedFn, const Monad<T>& x) {
        static_assert(is_monad<Monad>{}(), "");
        return wrappedFn >>= [x] (auto&& x1) { return x >>= [x1 = std::forward<decltype(x1)>(x1)] (auto&& x2) {
            return Monad<decltype(std::declval<funcType>()(std::declval<T>()))> { x1 (std::forward<decltype(x2)>(x2)) }; }; };
    }
    
    // convenience function to lift arbitrary values into the monad, i.e.
    // just a wrapper for the constructor that takes a single argument.
    template <template <typename, typename...> class Monad, typename T>
    Monad<std::remove_const_t<std::remove_reference_t<T>>> pure(T&& val) {
        static_assert(is_monad<Monad>{}(), "");
        return Monad<std::remove_const_t<std::remove_reference_t<T>>> { std::forward<decltype(val)>(val) };
    }
    
    // liftM
    template <template <typename, typename...> class Monad, typename funcType>
    auto liftM(funcType&& f) {
        static_assert(is_monad<Monad>{}(), "");
        return [_f = std::forward<decltype(f)>(f)] (auto x) {
            return ap(pure<Monad>(_f), x);
        };
    }
    
    // fmap
    template <template <typename, typename...> class Monad, typename T, typename funcType>
    auto fmap(funcType&& f, Monad<T> const& x) {
        static_assert(is_monad<Monad>{}(), "");
        return x >>= ( [_f = std::forward<funcType>(f)] (const T& val) {
            return Monad<decltype(_f(std::declval<T>()))> {_f(val)}; });
    }
    

    让我们看看如何使用它,假设您已经实现了 operator>>=std::vectoroptional .
    // functor similar to std::plus<>, etc.
    template <typename T = void>
    struct square {
        auto operator()(T&& x) {
            return x * std::forward<decltype(x)>(x);
        }   
    };
    
    template <>
    struct square<void> {
        template <typename T>
        auto operator()(T&& x) const {
            return x * std::forward<decltype(x)>(x);
        }
    };
    
    int main(int, char**) {
        auto vector_empty = std::vector<double>{};
        auto vector_with_values = std::vector<int>{2, 3, 31};
        auto optional_with_value = optional<double>{42.0};
        auto optional_empty = optional<int>{};
    
        auto v1 = liftM<std::vector>(square<>{})(vector_empty); // still an empty vector
        auto v2 = liftM<std::vector>(square<>{})(vector_with_values); // == vector<int>{4, 9, 961};
        auto o1 = liftM<optional>(square<>{})(optional_empty); // still an empty optional
        auto o2 = liftM<optional>(square<>{})(optional_with_value); // == optional<int>{1764.0};
    
        std::cout << std::boolalpha << is_monad<std::vector>::value << std::endl; // prints true
        std::cout << std::boolalpha << is_monad<std::list>::value << std::endl; // prints false
    
    }
    

    限制

    虽然这允许使用通用方法来定义 monad 的概念,并可以直接实现 monadic 类型构造函数,但还是存在一些缺点。

    首先,我不知道有一种方法可以让编译器推断出使用哪个类型构造函数来创建模板化类型,即我知道没有办法让编译器弄清楚 std::vector模板已用于创建类型 std::vector<int> .因此,您必须在调用中手动添加类型构造函数的名称以实现例如fmap .

    其次,编写适用于通用 monad 的函数非常难看,正如您在 ap 中看到的那样。和 liftM .另一方面,这些必须只写一次。最重要的是,一旦我们获得概念(希望在 C++2x 中),整个方法将变得更容易编写和使用。

    最后但并非最不重要的一点是,按照我在这里写的形式,Haskell 的 monad 的大部分优点都无法使用,因为它们严重依赖于柯里化。例如。在这个实现中,你只能将函数映射到只接受一个参数的 monad 上。在我的 github你可以找到一个也支持柯里化的版本,但语法更糟。

    对于感兴趣的人,这里是 coliru .

    编辑:我刚刚注意到我错了,编译器无法推断 Monad = std::vectorT = int当提供类型为 std::vector<int> 的参数时.这意味着你真的可以有一个统一的语法来使用 fmap 将函数映射到任意容器上。 , IE。
    auto v3 = fmap(square<>{}, v2);
    auto o3 = fmap(square<>{}, o2);
    

    编译并做正确的事情。

    我将示例添加到了coliru。

    编辑:使用概念

    由于 C++20 的概念即将到来,并且语法几乎是最终版本,因此使用使用概念的等效代码更新此回复是有意义的。

    使用概念可以做的最简单的事情是编写一个包含 is_monad 类型特征的概念。
    template<template<typename, typename...> typename T>
    concept monad = is_monad<T>::value;
    

    不过,它也可以单独写成一个概念,这样会更清晰一些。
    template<template<typename, typename...> typename Monad>
    concept monad = requires {
        std::is_same_v<monadic_bind_t<Monad, DummyType, DummyType2>, Monad<DummyType2>>;
        std::is_same_v<constructor_return_t<Monad, DummyType>, Monad<DummyType>>;
    };
    

    这允许我们做的另一件事是清理上面通用 monad 函数的签名,如下所示:
    // fmap
    template <monad Monad, typename T, typename funcType>
    auto fmap(funcType&& f, Monad<T> const& x) {
        return x >>= ( [_f = std::forward<funcType>(f)] (const T& val) {
            return Monad<decltype(_f(std::declval<T>()))> {_f(val)}; });
    }
    

    关于c++ - C++ 中的 Monad 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39725190/

    有关c++ - C++ 中的 Monad 接口(interface)的更多相关文章

    1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

      总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

    2. ruby - 其他文件中的 Rake 任务 - 2

      我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

    3. ruby-on-rails - Ruby net/ldap 模块中的内存泄漏 - 2

      作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代

    4. ruby-on-rails - Rails 3 中的多个路由文件 - 2

      Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

    5. ruby-on-rails - Rails - 一个 View 中的多个模型 - 2

      我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何

    6. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

      我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

    7. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

      我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

    8. ruby-on-rails - Rails 应用程序中的 Rails : How are you using application_controller. rb 是新手吗? - 2

      刚入门rails,开始慢慢理解。有人可以解释或给我一些关于在application_controller中编码的好处或时间和原因的想法吗?有哪些用例。您如何为Rails应用程序使用应用程序Controller?我不想在那里放太多代码,因为据我了解,每个请求都会调用此Controller。这是真的? 最佳答案 ApplicationController实际上是您应用程序中的每个其他Controller都将从中继承的类(尽管这不是强制性的)。我同意不要用太多代码弄乱它并保持干净整洁的态度,尽管在某些情况下ApplicationContr

    9. ruby-on-rails - form_for 中不在模型中的自定义字段 - 2

      我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢

    10. ruby - rspec 需要 .rspec 文件中的 spec_helper - 2

      我注意到像bundler这样的项目在每个specfile中执行requirespec_helper我还注意到rspec使用选项--require,它允许您在引导rspec时要求一个文件。您还可以将其添加到.rspec文件中,因此只要您运行不带参数的rspec就会添加它。使用上述方法有什么缺点可以解释为什么像bundler这样的项目选择在每个规范文件中都需要spec_helper吗? 最佳答案 我不在Bundler上工作,所以我不能直接谈论他们的做法。并非所有项目都checkin.rspec文件。原因是这个文件,通常按照当前的惯例,只

    随机推荐