4

皆様、

私は最近、いくつかの F# に手を出していて、いくつかの C# コードから移植した次の文字列ビルダーを思いつきました。属性で定義された正規表現を渡す場合、オブジェクトを文字列に変換します。目の前のタスクにはおそらくやり過ぎですが、学習目的のためです。

現在、BuildString メンバーは変更可能な文字列変数 updatedTemplate を使用しています。私は、可変オブジェクトなしでこれを行う方法を見つけ出すために頭を悩ませてきましたが、役に立ちませんでした。それが私の質問につながります。

変更可能なオブジェクトなしで BuildString メンバー関数を実装することは可能ですか?

乾杯、

マイケル

//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
4

3 に答える 3

1

「効果が 1 つしかないシーケンスの for ループ (ローカル変数の変更)」を、変更可能なものを取り除くコードにいつでも変換できると思います。一般的な変換の例を次に示します。

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

特定の例にはネストされたループがあるため、同じ種類の機械的変換を 2 つのステップで示す例を次に示します。

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

(上記のコードでは、スコープを明確にするために「x2」と「x3」という名前を使用しましたが、全体を通して「x」という名前を使用できます。)

サンプルコードでこれと同じ変換を行い、独自の回答を投稿することは価値があるかもしれません. これは、必ずしも最も慣用的なコードを生成するわけではありませんが、for ループを Seq.fold 呼び出しに変換する演習になる可能性があります。

(とは言っても、この例では、全体の目標は主に学術的な演習です。ミュータブルを含むコードは「問題ありません」。)

于 2009-05-21T07:03:17.773 に答える
1

純粋に機能的なアプローチ:

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
于 2009-07-21T17:47:30.257 に答える
1

これをコードとして書き上げる時間はありませんが、

  • 文字列 (ここまでの結果) とプロパティと属性のタプルを取り、置換後の文字列を返す、最も内側の部分を表す関数を作成します。
  • seq.map_concatによって返されるプロパティGetProperties()の配列から (プロパティ、属性) タプルのシーケンスに移動するために使用します。
  • seq.fold元のテンプレートを集計の初期値として使用して、変換全体を行うために前の 2 ビットと共に使用します。全体的な結果は、最終的に置換された文字列になります。

それは理にかなっていますか?

于 2009-05-21T06:26:31.067 に答える