I am trying to make a kind of specialization of a generic type.
The problem is to make an AVL tree in a generic way, to make a custom map between a key k and a data item d. I want to use as much of the generic approach as possible but provide a custom lookup: if the AVL tree type has a key of 'DateRange' type, then I can ask if it contains a DateTime and it will return the first node where the DateRange contains that DateTime.
In general I have:
type AvlTree<'k,'d when 'k:comparison and 'd:equality>
(
tree : tree<'k,'d>
)=
member this.Contains(k) = contains k tree
let rec contains k = function // appears above. Moved here for clarity of exposition
| Nil -> None
| Node(_, l, (kx,dx), r) ->
if k = kx then Some(dx)
else
if k < kx then contains k l
else contains k r
(I am using http://en.wikibooks.org/wiki/F_Sharp_Programming/Advanced_Data_Structures#AVL_Trees as a template)
I'm trying to extend it like this:
type AvlTree<'k,'d when 'k :> DateRange and 'd:equality> with
member this.Contains(k:DateTime) = splcontains k **tree**
so the idea is that if the tree type itself has a DateRange key type, and we are doing lookup on a DateTime, then we use a special 'contains' function.
Is this even possible? If so, how do I do it.
My compiler is currently telling me 'The value or constructor 'tree' is not defined' on the highlighted part above. I don't understand this, because essentially identical code works fine in the main type definition. Are you not allowed to access data members in a 'with' construct?
tree
. It is just not visible. If you define a new property for access totree
and use that in the extension, everything will compile. However, the specialization will never be used (see other comments).