简体   繁体   English

Haskell相当于C ++类型的对

[英]Haskell equivalent of C++ typed pair

I'm think of converting following C++ code into Haskell 我想把以下C ++代码转换成Haskell

#include <utility>

template<typename Pair>
struct inv_pair
{
    typedef std::pair<
        typename Pair::second_type, 
        typename Pair::first_type
    > type;
};

The inv_pair basically invert pair's first_type and second_type. inv_pair基本上反转了对的first_type和second_type。 It can be used as follows 它可以如下使用

typedef std::pair<int, std::string> pair_t1;    
typedef inv_pair<pair_t1>::type inv_par_t1; 
// of type std::pair<std::string, int>

Haskell 哈斯克尔

data Pair' = Pair' Int String
-- then?

Maybe it's not an useful pattern. 也许这不是一个有用的模式。 Still curious and willing to learn. 仍然好奇并愿意学习。

In Data.Tuple there's already a function called swap which does what you need. Data.Tuple ,已经有一个名为swap的函数Data.Tuple您的需求。 It's type is: 它的类型是:

swap :: (a, b) -> (b, a)

As an example the following: 以下是一个例子:

import Data.Tuple

tuple :: (Int, String)
tuple = (1, "OK")

main = putStr $ (fst . swap) tuple

Live demo 现场演示

will print OK . 会打印OK


On a side note, the data constructor for pairs is (,) which can be called (thanks to syntactic sugar) as: 另一方面,对的数据构造函数是(,)可以调用(由于语法糖):

(a, b)

instead of: 代替:

(,) a b

So you could also flip the data constructor for pairs. 所以你也可以翻转对的数据构造函数。 For example: 例如:

flip (,)

will produce a data constructor with reversed arguments. 将生成一个反向参数的数据构造函数。 So that: 以便:

reversedTuple :: b -> a -> (a, b)
reversedTuple = flip (,)

main = putStr $ fst $ reversedTuple "First" "Second"

Live demo 现场演示

will print Second . 将打印Second

Haskell has built-in tuples. Haskell内置了元组。 For example (3, "foo") has type (Int, String) . 例如(3, "foo")具有类型(Int, String)

Creating the "inverted" pair is easy. 创建“倒”对很容易。 For example the following function swaps the two entries of a pair: 例如,以下函数交换一对的两个条目:

swap (x, y) = (y, x)

and its type can be written down as 它的类型可以写成

swap :: (a, b) -> (b, a)

A possible Haskell translation of the following C++ type hackery 以下C ++类型hackery的可能Haskell转换

template<typename Pair>
struct inv_pair
{
    typedef std::pair<
        typename Pair::second_type, 
        typename Pair::first_type
    > type;
};

typedef std::pair<int, std::string> pair_t1;
typedef inv_pair<pair_t1>::type inv_pair_t1; 

could be the following 可能是以下

{-# LANGUAGE TypeFamilies #-}
type family Swap t 
type instance Swap (a,b) = (b,a)

type Pair_t1     = (Int, String)
type Inv_Pair_t1 = Swap Pair_t1

I am not so sure this would be useful in practice, though. 不过,我不太确定这在实践中是否有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM