2016-06-01 2 views
6

이것은 순수 학문적 인 질문이지만 형식 제한에 대해서는 this question 입니다. 질문자는이를 예로 들어 설명했습니다.재귀 유형 제약 조건을 가진 객체를 만들 수 없습니까?

type Something<'a, 'b when 'b :> seq<'b>>() = 
    member __.x = 42 

행복하게 컴파일합니다. 이제 문제는 어떻게이 객체를 만드는 것입니까 ??

open System.Collections.Generic 

type Node<'a>() = 
    let getEmptyEnumerator() = Seq.empty<Node<'a>>.GetEnumerator() 
    interface IEnumerable<Node<'a>> with 
     member this.GetEnumerator() = getEmptyEnumerator() 
     member this.GetEnumerator() = 
      getEmptyEnumerator() :> System.Collections.IEnumerator 

대신 빈 시퀀스를 반환하는, 당신은 자식 노드의 시퀀스를 반환하는이 클래스를 구현할 수

:

let z = new Something<???, ???>() 
+3

이의 비 인위적인 예를 들어 https://msdn.microsoft.com/en-us/library/documentformat.openxml.openxmlelement(v=office.14).aspx 참조 사용할 수있는 클래스. – kvb

+1

어쩌면 당신은'불가능한'이라는 단어를 제거하기 위해 제목을 바꾸어야 할 것입니다.'이걸로 머리를 잡지 못해 ' –

+0

@kvb 맞아. 'let z = new Something ()'이 작동합니다. – Ray

답변

3

여기에 하나의 방법입니다. 이 유형은 Node<'a>이라고 불렀습니다. C#에서 트리 (또는 그래프)를 모델링하는 것은 상당히 관례적인 방식이기 때문입니다.

사용 :

> let smth = Something<string, Node<int>>();;  
val smth : Something<string,Node<int>> 

> smth.x;; 
val it : int = 42 
4
type T() = 
    interface seq<T> with 
     member this.GetEnumerator() = ([] :> seq<T>).GetEnumerator() 
     member this.GetEnumerator() = ([] :> seq<T>).GetEnumerator() :> System.Collections.IEnumerator 

let z = new Something<string, T>() 
관련 문제