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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With