Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a list to a tuple in Haskell?

Tags:

haskell

How can I best convert a list to a tuple in Haskell:

[1,2,3,4,5,6] -> (1,2,3,4,5,6) 
like image 571
Alex Avatar asked May 27 '10 13:05

Alex


People also ask

How do you convert an element to a list to a tuple?

To convert the Python list to a tuple, use the tuple() function. The tuple() is a built-in function that passes the list as an argument and returns the tuple. The list elements will not change when it converts into a tuple. This is the easiest approach for conversion.

How do you make a tuple in Haskell?

Use parentheses and commas to create tuples. Use one comma to create a pair. Use more commas to create tuples with more components. Note that it is also possible to declare tuples using in their unsugared form.

What function converts a list to a tuple?

You can convert a list into a tuple simply by passing to the tuple function.

How do you define a tuple in Haskell?

A tuple is a fixed-length coupling of values, written in parentheses with the values separated by commas. One way to use this is to pass all parameters into a function as one value, rather than the curried functions we've seen so far.


2 Answers

In a general way, you can't. Each size of tuple is a distinct type, whereas lists of any length are a single type. Thus, there's no good way to write a function that takes a list and returns a tuple of the same length--it wouldn't have a well-defined return type.

For instance, you could have functions like:

tuplify2 :: [a] -> (a,a) tuplify2 [x,y] = (x,y)  tuplify3 :: [a] -> (a,a,a) tuplify3 [x,y,z] = (x,y,z) 

...but not one that does the job of both.

You can write a generic version using various kinds of meta-programming, but you'd rarely want to.

Note that the same problem applies to other things, such as writing class instances for various tuples--take a look at the source code for Data.Tuple from the standard libraries!

like image 198
C. A. McCann Avatar answered Sep 23 '22 13:09

C. A. McCann


Template Haskell is as close as you can get due to type checking if you want to extract a variable number of elements, since (a,b) and (a,b,c) have different types.

{-# LANGUAGE TemplateHaskell #-} import Language.Haskell.TH tuple :: Int -> ExpQ tuple n = do     ns <- replicateM n (newName "x")     lamE [foldr (\x y -> conP '(:) [varP x,y]) wildP ns] (tupE $ map varE ns) 

Then:

$(tuple 6) [1,2,3,4,5,6] == (1,2,3,4,5,6) $(tuple 3) "abc" == ('a','b','c') 

But in general, if you need this answer, then you're asking the wrong question somewhere.

If you just want flat random access, perhaps the better option would be to use an Array.

like image 40
Edward Kmett Avatar answered Sep 22 '22 13:09

Edward Kmett