How to handle inconsistent lists for the Zip algorithm

I'm going to write a Delphi implementation of a functional Zip routine that takes two lists and outputs a list of pairs of items. So feeding it [1, 2, 3] and ['a', 'b', 'c'] will give [(1, 'a'), (2, 'b'), (3, c)) ] as a result. It's great if both inputs are the same length, as in every demo I've seen of this feature online. But what if the first one was [1, 2, 3, 4]? What should be the way out? How is this case handled in other implementations in other languages?

+2


source to share


3 answers


There is no "right" or "wrong" way to do this, the implementation details are up to you. You can use several approaches:

1) F # Approach: Exception.

2) Haskell and Python approach: Truncate the output to the minimum length of your inputs.

zip [1; 2; 3] ['a'; 'b'; 'c'; 'd'; 'e']
  = [ (1, 'a'); (2, 'b'); (3, 'c')]

      

It can sometimes be useful to trim, as is usually the case when you are looping a finite and infinite sequence.



3) Ruby approach: null or null inaccessible values:

zip [1; 2; 3] ['a'; 'b'; 'c'; 'd'; 'e']
  = [ (1, 'a'); (2, 'b'); (3, 'c'); (nil, 'd'); (nil, 'e')]

      

4) Truncate the tuples. 2 and 1 tuples as needed:

zip [1; 2; 3] ['a'; 'b'; 'c'; 'd'; 'e']
  = [ (1, 'a'); (2, 'b'); (3, 'c'); ('d'); ('e')]

      

I don't know any language that does this.

+10


source


It is common knowledge to button up the list with your tail. For example, to turn a list of points into a path that visits those points. The tail is obviously one shorter than the list, but this is certainly not an exceptional case. Another common thing is to freeze a list with all its tails to get a list of unordered pairs that can be built from the list (to plot a complete graph, e.g .:

liftM2 (=<<) zip tails

      



It would be really tricky if zip

throwing exceptions or returning null. Therefore, the expected behavior is to truncate the output by the length of a shorter list. This corresponds to the type of function.

+2


source


Python truncates the length of the minimum sequence. This works for me.

+1


source







All Articles