Pergunta

Gday All,

I foram dabbling em alguns F # da tarde e eu vim com o seguinte construtor string que eu portado de algum código C #. Ele converte um objeto em uma cadeia, desde que passa um Regex definido nos atributos. É provavelmente um exagero para a tarefa em mãos, mas a sua para fins de aprendizagem.

Atualmente, o membro BuildString usa um updatedTemplate cadeia variável mutável. I foram quebrando a cabeça para descobrir uma maneira de fazer isso sem objetos mutáveis ??sem sucesso. O que me leva à minha pergunta.

É possível implementar a função de membro BuildString sem objetos mutáveis?

Cheers,

Michael

//The Validation Attribute
type public InputRegexAttribute public (format : string) as this =
    inherit Attribute()
    member self.Format with get() = format

//The class definition
type public Foo public (firstName, familyName) as this =
    [<InputRegex("^[a-zA-Z\s]+$")>]
    member self.FirstName with get() = firstName 

    [<InputRegex("^[a-zA-Z\s]+$")>]
    member self.FamilyName with get() = familyName 

module ObjectExtensions =
    type System.Object with
        member this.BuildString template =
            let mutable updatedTemplate : string  = template
            for prop in this.GetType().GetProperties() do
                for attribute in prop.GetCustomAttributes(typeof<InputRegexAttribute>,true).Cast<InputRegexAttribute>() do
                    let regex = new Regex(attribute.Format)
                    let value = prop.GetValue(this, null).ToString()
                    if regex.IsMatch(value) then
                        updatedTemplate <- updatedTemplate.Replace("{" + prop.Name + "}", value)
                    else
                        raise (new Exception "Regex Failed")
            updatedTemplate

open ObjectExtensions
try
    let foo = new Foo("Jane", "Doe")
    let out = foo.BuildInputString("Hello {FirstName} {FamilyName}! How Are you?")
    printf "%s" out
with | e -> printf "%s" e.Message
Foi útil?

Solução

Eu acho que você sempre pode transformar um "loop sobre uma seqüência com apenas um efeito (mutando uma variável local)" para o código que se livrar do mutável; aqui está um exemplo do general transformação:

let inputSeq = [1;2;3]

// original mutable
let mutable x = ""
for n in inputSeq do
    let nStr = n.ToString()
    x <- x + nStr
printfn "result: '%s'" x

// immutable
let result = 
    inputSeq |> Seq.fold (fun x n ->
        // the 'loop' body, which returns
        // a new value rather than updating a mutable
        let nStr = n.ToString()
        x + nStr
    ) ""  // the initial value
printfn "result: '%s'" result

Seu exemplo particular tem laços aninhados, então aqui está um exemplo de mostrar o mesmo tipo de mecânica transformar em duas etapas:

let inputSeq1 = [1;2;3]
let inputSeq2 = ["A";"B"]

let Original() = 
    let mutable x = ""
    for n in inputSeq1 do
        for s in inputSeq2 do
            let nStr = n.ToString()
            x <- x + nStr + s
    printfn "result: '%s'" x

let FirstTransformInnerLoopToFold() = 
    let mutable x = ""
    for n in inputSeq1 do
        x <- inputSeq2 |> Seq.fold (fun x2 s ->
            let nStr = n.ToString()
            x2 + nStr + s
        ) x
    printfn "result: '%s'" x

let NextTransformOuterLoopToFold() = 
    let result = 
        inputSeq1 |> Seq.fold (fun x3 n ->
            inputSeq2 |> Seq.fold (fun x2 s ->
                let nStr = n.ToString()
                x2 + nStr + s
            ) x3
        ) ""
    printfn "result: '%s'" result

(No código acima, eu usei os nomes 'x2' e 'x3' para fazer o escopo mais aparente, mas você pode apenas usar o nome 'x' por toda parte.)

Pode ser útil para tentar fazer isso mesmo transformar em seu código de exemplo e postar a sua própria resposta. Isso não vai necessariamente produzir o código mais idiomática, mas pode ser um exercício de transformar um loop em uma chamada Seq.fold.

(Dito isto, neste exemplo todo o objetivo é principalmente um exercício acadêmico -. O código com os é mutável 'bem')

Outras dicas

Eu não tenho o tempo para escrever isso como código, mas:

  • Escreva uma função que representa a parte mais interna, tomando uma corda (o resultado até agora) e uma tupla da propriedade eo atributo, e retornando a string após a substituição.
  • Uso seq.map_concat ir desde a matriz de propriedades retornados por GetProperties() a uma sequência de (propriedade, atributo de tuplos).
  • Use seq.fold com os dois bits anteriores para fazer toda a transformação, utilizando o modelo original como o valor inicial para a agregação. O resultado global será a seqüência substituído final.

Isso faz sentido?

Uma abordagem puramente funcional:

module ObjectExtensions =
type System.Object with
    member this.BuildString template =
        let properties = Array.to_list (this.GetType().GetProperties())
        let rec updateFromProperties (pps : Reflection.PropertyInfo list) template =
            if pps = List.Empty then
                template
            else 
                let property = List.hd pps
                let attributes = Array.to_list (property.GetCustomAttributes(typeof<InputRegexAttribute>,true))
                let rec updateFromAttributes (ats : obj list) (prop : Reflection.PropertyInfo) (template : string) =
                    if ats = List.Empty then
                        template
                    else
                        let a = (List.hd ats) :?> InputRegexAttribute
                        let regex = new Regex(a.Format)
                        let value = prop.GetValue(this, null).ToString()
                        if regex.IsMatch(value) then
                            template.Replace("{" + prop.Name + "}", value)
                        else
                            raise (new Exception "Regex Failed\n")
                updateFromProperties(List.tl pps) (updateFromAttributes attributes property template)
        updateFromProperties properties template
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top