Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

haskell

tuples

I have to get nth element in a Haskell tuple. And the tuples are like this : (3,5,"String1","String2","String3","String4","String5","String6","String7","String8","String9","String10"). Can you give me an idea so that I can solve this problem? Thanks.

like image 475
jason Avatar asked Mar 21 '13 21:03

jason


People also ask

How do you get the second element in a tuple Haskell?

2. snd. This tuple function is used to get the second element from the tuple values or group. We can use this function before the tuple and it will return us the second element as the result in Haskell.

What is 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

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.

like image 60
DiegoNolan Avatar answered Sep 28 '22 21:09

DiegoNolan


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.

like image 37
Tikhon Jelvis Avatar answered Sep 28 '22 22:09

Tikhon Jelvis