Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are arbitrary sized tuples useful? (Template Haskell)

In the introductory text for Template Haskell one of the examples for why Template Haskell is useful is working with arbitrary sized tuples.

What is the purpose of arbitrary sized tuples? If the data type is the same why not use a list? And if the data types in the tuple are different, how can it be expanded to arbitrary sizes?

like image 255
user668074 Avatar asked Dec 15 '22 09:12

user668074


1 Answers

With arbitrary one means arbitrary at compile time. So if you want tuples with fifteen elements, template Haskell will generate a function for a tuple with fifteen elements. After compilation however, the number of elements is fixed. The advantage of using a tuple is that you can access each element in constant time O(1). So you can use the type system to enforce the tuple still contains a fixed amount of elements.

Furthermore the sel in the example can work with tuples where the elements have arbitrary types. For instance sel 2 3 will generate a function:

$(sel 2 3) :: (a,b,c) -> b
$(sel 5 5) :: (a,b,c,d,e) -> e

whereas if you use a list [a], this means that the list can only contain data for a certain type:

(!!3) :: [a] -> a

so all items have type a. Furthermore in this case you are not sure that the list will have three elements. The more you can check at compile time, the more safe your code is (and in many cases more efficient as well).

A list on the other hand has an arbitrary size at runtime. The same type - for instance [Int] - can specify a list with two, five, hundred or thousands of integers. Furthermore in the case of a list, accessing the k-th element requires O(k) time. There are datastructures like arrays that of course can access elements in constant time.

like image 131
Willem Van Onsem Avatar answered Dec 30 '22 14:12

Willem Van Onsem