F#は可変に変更でき
-
23-08-2019 - |
質問
Gday、
私ツ一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
解決
私はあなたが常に可変を取り除くコードに「一つだけ効果(ローカル変数を変異)でシーケンスをループするための」変革することができると思います。ここでの例です一般的な転換ます:
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」の名前を使用することができます。)
同じあなたのサンプルコードに変換し、あなた自身の答えを投稿やろうする価値があるかもしれません。これは、必ずしも最も慣用的なコードが得られませんが、Seq.fold呼び出しにループのための転換に運動することができます。
(つまり、この例では、全体の目標は、主に学術的な運動である、と述べた - 。可変とコードは「罰金」です)
他のヒント
思っていたのをはじめとして、コードが
- 書き機能の最深部は、文字列の結果、これまで)のタプルは財産の属性の文字列の後に交換できます。
- 使用
seq.map_concat
になっていくことになるでしょう配列の物件で返されるGetProperties()
へのシーケンス(有の属性)タプル. - 使用
seq.fold
前二つのビットを変換を使用し、独自のテンプレートとしての初期値を集計するために全体の結果と大きく異なる結果となる可能置換文字列になります。
ます。
純粋に機能的なアプローチ:
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
所属していません StackOverflow