Caso especial para tipo genérico con extensión

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)
            if k < kx then contains k l
            else contains k r

(Estoy usando 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?

preguntado el 31 de julio de 12 a las 13:07

Found a similar issue here:… Turns out this can't be done. I worked around it by making an inherited type with a different name: type DTTree<'d when 'd:equality> ( tree : tree<DateRange,'d> )= inherit AvlTree<DateRange,'d>(tree) member this.Contains(k:DateTime) = splcontains k tree -

Sorry, I didn't read the question closely enough. You're right. -

Regarding the error message: Yes, you are not allowed to access tree. It is just not visible. If you define a new property for access to tree and use that in the extension, everything will compile. However, the specialization will never be used (see other comments). -

0 Respuestas

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.