How to pattern match empty vector in Haskell?

Let's say I want to implement a length function for lists using pattern matching, then I could do something like this:

length' :: (Num b) => [a] -> b length' [] = 0 length' (_:xs) = 1 + length' xs 

Is it possible to do something similar with Vector s?

+5
source share
1 answer

The vector library of various types of vector are opaque types that do not expose their data constructors, and therefore you cannot match them with patterns.

There are ways around this, such as ViewPatterns (as user comment ViewPatterns mentions), but you certainly don't want to use them with vectors because you are likely to throw away the advantage of using vectors.

The highlight of the vector library is that it is implemented on the basis of two concepts:

  • Vectors materialize as fixed-size arrays, contiguous arrays of memory that provide much better memory locality than singly linked lists or trees;
  • A large number of vector operations are implemented in terms of fusible flows, the operations of which are reduced to cycles that do not allocate memory for intermediate vectors.

(1) means that the vector does not have a natural β€œhead” and β€œtail”, like lists of lists, in the literal sense it is a pair of head and tail. If you used some kind of view template to overlay the head + tail structure on top of the vector, you would effectively create a simply connected list of vector elements, which is likely to cause memory allocation for each node of the view type.

And if you used ViewPatterns to view a vector as an effective single linked list, why not just convert the vector to a list?

In any case, due to the design points mentioned above, with vector you really want to stick to the operations provided by the library itself as much as possible, since they will use the library's performance features.

I suspect that there is a good chance that testing vector size might be a suboptimal idea in many contexts. For example, in code, for example:

 example :: Vector something -> Vector somethingElse example as | Vector.null as = ... | otherwise = ... 

... I would expect (but not check!) That this would cause the vector as be materialized, so that we can check whether it is empty or not, where if the test could be eliminated or moved to another place it is possible that operations in the bit "..." can be combined with the context in which example used.

+3
source

Source: https://habr.com/ru/post/1247143/


All Articles