Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count the length of a tuple in Haskell?

Tags:

haskell

I tried searching in web and stackexchange, but surprisingly no one asked how to calculate length of a tuple in Haskell in the form below.

So suppose you have tuple like (1,2,3,4) or (1,3,5,6,7) in Haskell and wish to write the length function that calculates length of a tuple. How can I do this? For list I know how I will be able to do so using recursion without explicitly invoking built-in functions. But tuple is different, and I can't use "head"-"tail" distinction.

Will the method involve creating a new data type?

like image 308
Lucia Guzheim Avatar asked Dec 06 '25 19:12

Lucia Guzheim


1 Answers

The reason you don't find anything on this is that it doesn't make a lot of sense to count the length of a tuple:

  • It is pre-determined a compile time (i.e. you might just as well hard-code it)
  • There's not really much you could do with that information: unlike with e.g. a list, it's not possible to index specific entries in a generic tuple.

That said, it is possible to achieve your goal, however this shouldn't be a normal function but a type-level function, aka type family. Using singleton type nats:

{-# LANGUAGE TypeFamilies, DataKinds #-}
import Data.Singletons
import Data.Singletons.TypeLits

type family TupLength a :: Nat where
  TupLength () = 0
  TupLength (a,b) = 2
  TupLength (a,b,c) = 3
  TupLength (a,b,c,d) = 4
  -- ...
  TupLength x = 1

Then

> mapM_ print [ natVal (sing :: SNat (TupLength ()))
              , natVal (sing :: SNat (TupLength (Int,String,Double)))
              , natVal (sing :: SNat (TupLength Bool)) ]
0
3
1
like image 149
leftaroundabout Avatar answered Dec 08 '25 16:12

leftaroundabout



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!