Reputation: 419
I'm think of converting following C++ code into 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. 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.
Upvotes: 2
Views: 325
Reputation: 116174
A possible Haskell translation of the following C++ type hackery
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.
Upvotes: 1
Reputation: 76300
In Data.Tuple
there's already a function called swap
which does what you need. 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
will print 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"
will print Second
.
Upvotes: 8
Reputation: 119562
Haskell has built-in tuples. For example (3, "foo")
has type (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)
Upvotes: 4