Pergunta

Por que deixe ligações não é permitido em uma união discriminada? Presumo que tem a ver com ligações let sendo executado em um construtor padrão?

Em uma nota secundária alguma sugestão sobre como eu poderia reescrever AI_Choose seria apreciada. Eu quero manter a prioridade ponderada em uma tupla com o AI. Minha idéia é ter AI_Weighted_Priority herdar AI_Priority e substituir Escolha. Eu não quero lidar com fechando listas de diferentes comprimentos (má prática imo).

open AI

type Condition =
    | Closest of float
    | Min
    | Max
    | Average
    member this.Select (aiListWeight : list<AI * float>) =
        match this with
        | Closest(x) -> 
            aiListWeight 
            |> List.minBy (fun (ai, priority) -> abs(x - priority))
        | Min -> aiListWeight |> List.minBy snd
        | Max -> aiListWeight |> List.maxBy snd
        | Average -> 
            let average = aiListWeight |> List.averageBy snd
            aiListWeight 
            |> List.minBy (fun (ai, priority) -> abs(average - priority))

type AI_Choose =
    | AI_Priority of list<AI> * Condition
    | AI_Weighted_Priority of list<AI * float> * Condition

    // I'm sad that I can't do this    
    let mutable chosen = Option<AI>.None

    member this.Choose() =
        match this with
        | AI_Priority(aiList, condition) -> 
            aiList 
            |> List.map (fun ai -> ai, ai.Priority())
            |> condition.Select
            |> fst
        | AI_Weighted_Priority(aiList, condition) -> 
            aiList 
            |> List.map (fun (ai, weight) -> ai, weight * ai.Priority())
            |> condition.Select
            |> fst

    member this.Chosen
        with get() = 
            if Option.isNone chosen then
                chosen <- Some(this.Choose())
            chosen.Value
        and set(x) =
            if Option.isSome chosen then
                chosen.Value.Stop()
            chosen <- Some(x)
            x.Start()

    interface AI with
        member this.Start() =
            this.Chosen.Start()
        member this.Stop() =
            this.Chosen.Stop()
        member this.Reset() =
            this.Chosen <- this.Choose()
        member this.Priority() =
            this.Chosen.Priority()
        member this.Update(gameTime) =
            this.Chosen.Update(gameTime)
Foi útil?

Solução

não faria sentido para permitir que "vamos" dentro de ligação discriminados sindicatos. Penso que a razão por que não é possível é que os sindicatos discriminados ainda são baseadas no projeto OCaml enquanto os objetos vêm do mundo .NET. F # está tentando integrar estes dois, tanto quanto possível, mas provavelmente poderia ir mais longe.

De qualquer forma, parece-me que você está usando a união discriminar apenas para implementar algum comportamento interno do tipo AI_Choose. Nesse caso, você poderia declarar uma união discriminada separadamente e usá-lo para implementar o tipo de objeto.

Eu acredito que você poderia escrever algo como isto:

type AiChooseOptions =
    | AI_Priority of list<AI> * Condition
    | AI_Weighted_Priority of list<AI * float> * Condition

type AiChoose(aiOptions) = 
    let mutable chosen = Option<AI>.None
    member this.Choose() =
        match aiOptions with
        | AI_Priority(aiList, condition) -> (...)
        | AI_Weighted_Priority(aiList, condition) -> (...)
    member this.Chosen (...)
    interface AI with (...)

A principal diferença entre hierarquia de classe e sindicatos discriminados é quando se trata de extensibilidade. Classes tornar mais fácil para adicionar novos tipos enquanto os sindicatos discriminados torná-lo mais fácil de adicionar novas funções que o trabalho com o tipo (no seu caso AiChooseOptions), de modo que é provavelmente a primeira coisa a considerar ao projetar o aplicativo.

Outras dicas

Para quem estiver interessado acabei derivando AI_Priority e AI_Weighted_Priority de uma classe base abstrata.

[<AbstractClass>]
type AI_Choose() =
    let mutable chosen = Option<AI>.None

    abstract member Choose : unit -> AI

    member this.Chosen
        with get() = 
            if Option.isNone chosen then
                chosen <- Some(this.Choose())
            chosen.Value
        and set(x) =
            if Option.isSome chosen then
                chosen.Value.Stop()
            chosen <- Some(x)
            x.Start()

    interface AI with
        member this.Start() =
            this.Chosen.Start()
        member this.Stop() =
            this.Chosen.Stop()
        member this.Reset() =
            this.Chosen <- this.Choose()
        member this.Priority() =
            this.Chosen.Priority()
        member this.Update(gameTime) =
            this.Chosen.Update(gameTime)

type AI_Priority(aiList : list<AI>, condition : Condition) =
    inherit AI_Choose()
    override this.Choose() =
        aiList 
        |> List.map (fun ai -> ai, ai.Priority())
        |> condition.Select
        |> fst

type AI_Weighted_Priority(aiList : list<AI * float>, condition : Condition) =
    inherit AI_Choose()
    override this.Choose() =
        aiList 
        |> List.map (fun (ai, weight) -> ai, weight * ai.Priority())
        |> condition.Select
        |> fst

Revisitando este código acabei levando a sugestão de Tomas que acabou muito mais limpo.

type AiChooseOptions =
    | Priority of List<AI * Priority>
    | WeightedPriority of List<AI * Priority * float>
    member this.Choose(condition : Condition) =
        match this with
        | Priority(list) ->
            list 
            |> List.map (fun (ai, priority) -> ai, priority.Priority())
            |> condition.Select
        | WeightedPriority(list) ->
            list 
            |> List.map (fun (ai, p, weight) -> ai, p.Priority() * weight)
            |> condition.Select

type AiChoose(condition, list : AiChooseOptions ) =
    let mutable chosen = Unchecked.defaultof<AI>, 0.0

    interface AI with
        member this.Update(gameTime) =
            (fst chosen).Update(gameTime)

    interface Priority with
        member this.Priority() =
            chosen <- list.Choose(condition)
            (snd chosen)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top