Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type safe equal tuple sizes.

Tags:

haskell

How can I write best write a type signature in Haskell that best encapsulates the idea that a function must be passed a tuple of any length with all elements X, and a list of tuples (of the same length) with all elements Y?

I don't mind if the type passed is a "real" tuple some alternate data type, as long as I can enforce at compile time that both the tuple and the list of tuples have the same length.

Tuple N X -> [Tuple N Y] -> Z
like image 878
Clinton Avatar asked Aug 29 '26 18:08

Clinton


1 Answers

As zoran119 suggests, length-indexed vectors are the classic way to do this.

{-# LANGUAGE GADTs, DataKinds #-}

data Nat = Z | S Nat

data Vec n a where
  Nil :: Vec 'Z a
  Cons :: a -> Vec n a -> Vec ('S n) a

Now you can easily write

f :: Vec n X -> [Vec n Y] -> Z
like image 135
dfeuer Avatar answered Aug 31 '26 13:08

dfeuer



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!