How to get nth element from a 10-tuple in Haskell?

You could do it with pattern matching. Just like you can match against a two- or three-value tuple, you can match against a ten-value tuple.

let (_, _, _, _, _, _, _, _, _, x, _, _) = tuple in x

However, chances are you don't want to do that. If you're trying to get the nth value out of a tuple, you're almost definitely using the wrong type. In Haskell, tuples of different lengths are different types--they're fundamentally incompatible. Just like Int and String are different, (Int, Int) and (Int, Int, Int) are also completely different.

If you want a data type where you can get the nth element, you want a list: something like [String]. With lists, you can use the !! operator for indexing (which starts at 0), so you could just do:

myList !! 9

to get the 10th element.

Given your example, I suspect you want a type like (Int, Int, [String]) rather than a gigantic tuple. This will let you have two numbers and any number of strings; you can get the strings by index using the !! operator as above.


As you may or may not know fst and snd only work for 2-element tuples ie

fst' (a,b) = a

You have to write you own as far as I know

get5th (_,_,_,_,a,_,_,_,_,_) = a

As you can see you may want to define your own type.

Tags:

Tuples

Haskell