cheshire
cheshire

Reputation: 1159

Check if tuple or triple in haskell

Is there a way to check how many elements (,) has? I know I can access first and second element of a tuple with fst and snd but and thought I could somehow sum elements and then compare it with fst tuple snd tuple and check like this:

tuple = (1,2)

sum tuple == fst tuple + snd tuple

and then I get True for this case and get False for triple = (1,2,3). Eitherway I cant ask fst (1,2,3) nor I can do sum tuple

Is there a way to check if I have a tuple or not?

Something like this:

is_tuple :: (a,b) -> a
is_tuple (a,_) = a

but to get True when I input tuple and False when I give (1,2,3) or (1,2,3,4) and so on... as a input.

i.e:

is_tuple :: Tuple -> Bool
is_tuple x = if x is Tuple 
                then True
                else False

?

Upvotes: 0

Views: 1203

Answers (1)

Alexis King
Alexis King

Reputation: 43842

Is there a way to check how many elements (,) has?

No, because the answer is always 2.

The type (,) is the type constructor for a tuple of two values, or a 2-tuple. It is a distinct type from (,,), the constructor for 3-tuples. Likewise, both those types are distinct from (,,,), the constructor for 4-tuples, and so on.

When you write a function with type (Foo, Bar) -> Baz, the typechecker will reject any attempts to call the function with a tuple of a different number of values (or something that isn’t a tuple at all). Therefore, your isTuple function only has one logical implementation,

isTuple :: (a, b) -> Bool
isTuple _ = True

…since it is impossible to ever actually call isTuple with a value that is not a 2-tuple.

Without using typeclasses, it is impossible in Haskell to write a function that accepts a tuple of arbitrary size; that is, you cannot be polymorphic over the size of a tuple. This is because, unlike lists, tuples are heterogenous—they can contain values of different types. A function that accepts a tuple of varying length would have no way to predict which elements of the tuple are of which type, and therefore it wouldn’t be able to actually do anything useful.

Very rarely, when doing advanced, type-level trickery, it can be useful to have a type that represents a tuple of varying length, which in Haskell is frequently known as an HList (for heterogenous list). These can be implemented as a library using fancy typeclass machinery and type-level programming. However, if you are a beginner, this is definitely not what you want.

It is difficult to actually give advice on what you should do because, as a commenter points out, your question reads like an XY problem. Consider asking a different question that gives a little more context about the problem you were actually trying to solve that made you want to find the list of a tuple in the first place, and you’ll most likely get more helpful answers.

Upvotes: 7

Related Questions