Is there a way to write the following function in Haskell:
get_nth_element :: Int->(???)->(???)
get_nth_element n tpl = ...
I'm interested in a solution for tuples, not lists, for which the solution is trivial. The reason being that tuples can aggregate different types, of course.
The intermediate goal is to be able to write a function that given a tuple and a value it returns a tuple that adds the given value to the given tuple. The ultimate goal is to write a generic Cartesian product function that, given a tuple of n (potentially different types of) lists, returns the Cartesian product list of all the resulting n-dimensional tuples (using, say, applicative operators <$>, <*>
).
This can be achieved in C++ (using variadic templates and SFINAE), so I assume there should be a way to do it in Haskell.
[Update]
C++ (11 and above) has std::get<i>(tuple)
and std::tuple_cat
. For example this compiles and runs just as expected:
#include <iostream>
#include <tuple>
template<typename T, typename ...Args>
std::tuple<T,Args...> grow_tuple(T v, std::tuple<Args...> t)
{
return std::tuple_cat(std::make_tuple(v), t);
}
int main(void)
{
std::tuple<int, std::string> t1{1, "Howdy!"};
int i = 13;
auto t2 = grow_tuple(i, t1);
std::cout<<"("<<std::get<0>(t2)
<<","<<std::get<1>(t2)
<<","<<std::get<2>(t2)<<")\n";
std::cout<<"Done!"<<std::endl;
}
Essentially, a mechanism is needed here to handle a variadic list of types. I can hardly believe Haskell does not have that.
[Update] Note: this is not about accessing an a-priori known element from a tuple of a-priori known length. It's about accessing an element given by a variable index in an variable tuple (of length and type unknown a-priori). The former implies a fixed definition of a lambda accessor ((_,_,x,_,_) -> x)
where both position of interest in tuple and tuple length are known a-priori. While my question does not make any such a-priori known assumptions. The function signature I am looking for does not take such lambda accessor, but an integer argument for the positional index inside the tuple and a generic tuple argument (generic meaning of unknown length and contained types). Hence this question is different than Haskell - Accessing a Specific Element in a Tuple.
nth
element, and you'd probably need some custom types or typeclasses to do that. (see for example here). Why don't you just define your own type instead of (ab-)using tuples? – flawr