【问题标题】:Can C++ pattern of making structs to 'correspond' types be emulated in Haskell (template specialization)?可以在 Haskell(模板专业化)中模拟 C++ 使结构“对应”类型的模式吗?
【发布时间】:2021-07-08 14:19:36
【问题描述】:
template <typename T>
struct Corresponding;

template <>
struct Corresponding<int> {
    using CorrespondingT = boost::multiprecison::cpp_int;
};
template <typename T> using GetCorresponding = typename Corresponding<T>::CorrespondingT;

这可以用作

static_assert(std::is_same_v<GetCorresponding<int>, boost::multiprecision::cpp_int>); // true

其中Corresponding&lt;T&gt; 是包含别名的结构,对应类型为T,在编译时解析。 另一个例子是std::remove_ptr_t&lt;T*&gt;,它对应于T

我可以在 Haskell 中做类似的事情吗,例如

iAmAnInteger :: getCorresponding Int -- Integer

?

我不熟悉 Haskell 在编译时类型方面的能力,但这可能吗?

【问题讨论】:

    标签: c++ haskell template-specialization compile-time static-typing


    【解决方案1】:

    我不精通 C++,所以我不能 100% 确定您的示例代码在做什么,但乍一看类型族和等式似乎相似。

    {-# LANGUAGE TypeFamilies #-}
    
    type family Corresponding a
    type instance Corresponding Int = Integer
    
    foo :: Corresponding Int ~ Integer => ()
    foo = () -- compiles
    
    bar :: Corresponding Int ~ Bool => ()
    bar = () -- type error at any use site
    
    baz :: Corresponding Int
    baz = toInteger 3 -- compiles
    
    quux :: Corresponding Int
    quux = False -- type error
    

    【讨论】:

      猜你喜欢
      • 2018-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多