We can define function f
and g
like this:
f :: [a] -> [a] -> [a]
f = (++)
g :: [a] -> [a] -> [a]
g = zipWith (+)
Both f
and g
take two lists as parameters and return a new list, but they are different: f
returns a longer list whose length is the sum of the inputs', meanwhile g
processes lists with the same length. How to figure this out to Haskell?
What you want is to encode the length of lists into the type system. In other words, encode natural numbers in the type system and operations on them. This is possible, although it involves some type trickery. There are libraries to achieve this, one of them tagged-list.
TaggedList
is tagged with its length as a type-level natural number. Then the types of your functions would look likewhich gives clear distinction of what happens with the length of the lists.
See also Type arithmetic.