concept length in category idris

appears as: length, lengths, length, lengths, The length
Type-Driven Development with Idris

This is an excerpt from Manning's book Type-Driven Development with Idris.

Using a simple type, both input lists have type AnyList, as does the output list. Using a generic type, you can specify that the input lists are both lists of strings, as is the output list. The more-precise types mean that, for example, the output is clearly related to the input in that the element type is unchanged. Finally, using a dependent type, you can specify the sizes of the input and output lists. It’s clear from the type that the length of the output list is the sum of the lengths of the input lists. That is, a list of 3 strings appended to a list of 4 strings results in a list of 7 strings.

Figure 3.2. Calculating the lengths of words in a list. Notice that each input has a corresponding output, so the length of the output vector is always the same as the length of the input vector.

When dealing with user input, there’ll often be some properties of the data that you can’t know until runtime. The length of a vector is one example: once you’ve read the vector, you know its length, and from there you can check it and reason about how it relates to other data. But you could have a similar problem with any dependent data type that’s read from user input, and it would be better not to define a new type (like VectUnknown) every time this happens. Instead, Idris provides a more generic solution, dependent pairs.

  • Refine— For zipInputs_rhs_2, you have a new vector, vec2', which is the same as vec2 but with its length now guaranteed to be the same as the length of vec1, as you can confirm by looking at the type:
      len1 : Nat
      vec2' : Vect len1 String
      len2 : Nat
      vec2 : Vect len2 String
      vec1 : Vect len1 String
    --------------------------------------
    zipInputs_rhs_2 : IO ()
    You can therefore complete the definition by calling zip with vec1 and vec2', and then printing the result:
    case exactLength len1 vec2 of
         Nothing => putStrLn "Vectors are different lengths"
         Just vec2' => printLn (zip vec1 vec2')