1

There is a function called Map.partition that splits the map into 2 maps with one containing ALL elements that satisfy the predicate. The predicate takes a key and a value as arguments and examines each element of the map to determine which result map it belongs to.

My requirement is a special case of this. I have a map and I want to split into 2 maps based on whether or not the key is greater than or less than some value. This would be much more efficient as you only have to search the tree until the output of the predicate changes. The current implementation would be O(n) and what I am looking for would be O(log(n)). This should be straight forward for a custom tree implementation but I would prefer to use the built in collections if I can, before I roll my own.

Chechy Levas
  • 2,206
  • 1
  • 13
  • 28
  • 3
    I don't think maps are generally assumed to be ordered in any way, or guaranteed to preserve any kind of ordering. – TeaDrivenDev Jul 03 '19 at 17:39
  • 2
    @TeaDrivenDev, maps are implemented as red-black trees, a type of self balancing binary search tree. So they are ordered in the sense of a binary tree. – Chechy Levas Jul 03 '19 at 17:40
  • 2
    They look more like AVL trees, but still it's an implementation detail that is not exposed to the client code. There's no way of manipulating the underlying tree structure (outside of reflection I suppose). – scrwtp Jul 03 '19 at 23:31

1 Answers1

0

The documentation for the F# Maps can be found in the following link: https://msdn.microsoft.com/en-us/visualfsharpdocs/conceptual/collections.map-module-%5Bfsharp%5D Altough the operation you want to implement could be implemented in O(log(n)), it is not implemented in this module. The best option would be to use partition (would be O(n), as you said) or implement your own version of Map. You could also search for some code in github which implements a Red-Black Tree and include your own custom method for this operation.

Short Answer: No, there is not a method to split a Map based on the first node to satisfy a predicate.

EDIT: this -> the

Alonso Montero
  • 138
  • 1
  • 8