我正在嘗試使用F#來理解函式式編程,為此我開始了一個小專案,但我遇到了以下問題,似乎找不到任何優雅的解決方案。
我創建了Validation<'a>,它幾乎是專門的F# Result。Result<'a, Error list>,它幫助我處理驗證結果。
我有兩個執行一些驗證的函式,都有簽名:
我有兩個執行一些驗證的函式,都有簽名。
'a -> Validation< 'b>
還有第三個函式可以消耗帶有簽名的驗證過的引數:
'a -> 'b -> Validation<'c>
我想實作的是:
我想實作的是:
- 驗證引數'a 如果引數'a'的驗證通過,則驗證引數'b'。
- 如果引數'b的驗證通過,則向最終函式提供引數'a和'b 。
到目前為止,我使用apply函式來實作這樣的行為,但是當我試圖在這種情況下使用它時,結果型別是嵌套的Validation 編輯#1:以下是我目前的簡化代碼: 這里是處理驗證的型別: 有問題的函式是這個: 驗證功能: 消耗驗證引數的函式: 編輯#2:我嘗試使用@brianberns提供的解決方案,并為Validation<'a>型別實作了計算運算式: 編輯#2:我嘗試使用@brianberns提供的解決方案,并為Validation<'a>型別實作了計算運算式。
并且這樣使用: 雖然計算運算式讀起來肯定更好,但最終的結果仍然是完全一樣的[Validation<Validation>],因為 "formatReportAsText "函式也回傳被Validation包裹的結果。
為了在某種程度上合并堆疊的驗證,我使用了下面的函式,但對我來說,它似乎很笨重: 編輯 #3:在驗證計算運算式中添加 "ReturnFrom "函式以平鋪嵌套驗證后,驗證函式如期運行。
使用計算運算式的驗證函式的最終版本是: uj5u.com熱心網友回復: 有很多方法可以剝掉這只貓的皮,但大多數方法的核心是,每當你遇到像Validation<Validation<'c>>/code>,因為final函式本身回傳Validation。我想擺脫其中一個驗證,所以結果型別將是Validation<'c>。我試著用bind和變種的lift函式進行實驗,我發現這里,但結果還是一樣。嵌套匹配是這里唯一的選擇嗎?
[<Struct> ]
type Error = {
Message: 字串。
Code: int。
}
type Validation<'a> =
| Success of 'a> =
| Failure of Error list
let apply elevatedFunction elevatedValue =
match elevatedFunction, elevatedValue with
| Success func, Success value -> Success (func value)
| Success _, Failure errors -> Failure errors
| Failure errors, Success _ -> Failure errors
Failure currentErrors, Failure newErrors -> Failure ( currentErrors@newErrors )
let (<*>) = apply
let formatReport (unvalidatedLanguageName: string) (unvalidatedReport: UnvalidatedReport)。Validation<Validation<string> > =
Success formatReportAsText
<*> languageTranslatorFor unvalidatedLanguageName
<*> reportFrom unvalidatedReport
let languageTranslatorFor (unvalidatedLanguageName: string) 。Validation<Entry -> string> = ...
let reportFrom (unvalidatedReport: UnvalidatedReport) 。Validation<Report> = ...。
let formatReportAsText (languageTranslator: Entry -> string) (報告:Report)。Validation<string> = ...。
// Validation<'a> -> Validation< 'b> -> Validation<'a * 'b>
let zip firstValidation secondValidation =
match firstValidation, secondValidation with
| Success firstValue, Success secondValue -> Success(firstValue, secondValue)
| Failure errors, Success _ -> Failure errors
| Success _, Failure mistakes -> Failure mistakes
Failure firstErrors, Failure secondErrors -> Failure (firstErrors @ secondErrors)
// Validation<'a> -> ('a -> 'b) -> Validation<'b>
let map elevatedValue func =
match elevatedValue with
| Success value -> Success(func value)。
Failure validationErrors -> Failure validationErrors
type MergeValidationBuilder() =
成員 _.BindReturn(validation: Validation<'a>, func) = Validation.map validation func
成員 _.MergeSources(validation1, validation2) = Validation.zip validation1 validation2
let validate = MergeValidationBuilder()
let formatReport (unvalidatedLanguageName: string) (unvalidatedReport: UnvalidatedReport)。Validation<Validation<string> > =
驗證 = {
let! translator = languageTranslatorFor unvalidatedLanguageName
and! report = reportFrom unvalidatedReport
return formatReportAsText translator report
}
// Validation<Validation< 'a>> -> Validation<'a>
let merge (nestedValidation: Validation<Validation<'a> >)。Validation<'a> =
match nestedValidation with
| Success innerValidation ->
match innerValidation with ->
| Success value -> Success value
| Failure innerErrors -> Failure innerErrors
| Failure outerErrors -> Failure outerErrors
member _.ReturnFrom(validation)=validation
let formatReport (unvalidatedLanguageName: string) (unvalidatedReport: UnvalidatedReport) 。Validation<string> =
validate = {
let! translator = languageTranslatorFor unvalidatedLanguageName
and! report = reportFrom unvalidatedReport
return! formatReportAsText translator report
}
Validation<Validation<string>>這樣的嵌套容器時,你需要一些方法來 "平坦 "嵌套。對于像Validation這樣的型別,這很容易:
// Validation<Validation< 'a>> -> Validation<'a>
let join = function
| Success x -> x
| Failure errors -> Failure errors
你也可以選擇呼叫這個函式flatten,但它通常被稱為join。
你可能還會發現一個map函式很有用。這個也很簡單:
// ('a -> 'b) -> Validation<'a> -> Validation<'b>
let map f = function
| Success x -> Success (f x)
| Failure errors -> Failure errors
這樣一個map函式使Validation成為functor。
當你同時擁有map和join時,你可以always實作一個通常稱為bind的方法:
// ('a -> Validation<'b>) -> Validation<'a> -> Validation<'b>。
let bind f = map f > > join
扁平化或join嵌套容器的能力是使其成為單體的原因。雖然它是一個被神秘感和敬畏感包圍的詞,但它實際上只是:它是一個你可以平移的函式器。
然而,通常情況下,join和bind被反過來定義:
let bind f = function
| Success x -> f x
Failure errors -> Failure errors
let join x = bind id x
使用join,你可以通過扁平化嵌套容器來調整有問題的函式:
// string -> UnvalidatedReport -> Validation<string>
let formatReport (unvalidatedLanguageName: string) (unvalidatedReport: UnvalidatedReport)=
Success formatReportAsText
<*> languageTranslatorFor unvalidatedLanguageName
<*> reportFrom unvalidatedReport
|> 加入
然而,這并不是我的做法。雖然這種組合體操可能很有趣,但它們并不總是最易讀的解決方案。
計算運算式
。我更傾向于定義一個計算運算式,它可以像這樣做:
type ValidationBuilder () =
成員 _.Bind (x, f) = bind f x
成員 _.ReturnFrom x = x
let validate = ValidationBuilder ()
這樣,你就可以像這樣寫出所需的函式了:
// string -> UnvalidatedReport -> Validation<string>
let formatReport (unvalidatedLanguageName: string) (unvalidatedReport: UnvalidatedReport)=
驗證 {
let! l = languageTranslatorFor unvalidatedLanguageName
let! r = reportFrom unvalidatedReport
return! formatReportAsText l r
}
然而,這個版本的問題是,它沒有使用apply函式來把錯誤附加到一起。換句話說,它在遇到第一個錯誤時就會短路。
為了支持收集錯誤,我們需要一個新版本。
為了支持在不發生短路的情況下收集錯誤,你將需要一個支持應用性漏斗的計算構建器,就像 @brianberns 指出的那樣。你也可以看到一個例子這里。
。uj5u.com熱心網友回復:
首先,我認為你正在進入F#的一個相當高級的領域--但最實用的解決方案是使用計算構建器,正如@brianberns在評論中鏈接的前一個答案中所提到的。
如果你想堅持使用基于組合器的更簡單的方法,你可以使用以下函式來實作:
如果你想堅持使用基于組合器的更簡單的方法,你可以使用以下函式。
val merge 。Validation<'a> -> Validation< 'b> -> Validation<'a * 'b>
val bind : ('a -> Validation<'b>) -> Validation<'a> -> Validation<'b>
Merge是一個函式,它接收兩個可能被驗證的值,并產生一個新的值,將錯誤結合起來(就像你原來的apply函式)。Bind函式將一個函式應用于一個驗證過的值,并在結果中折疊 "嵌套 "驗證。它們可以被實作為:
let merge elevatedValue1 elevatedValue2 =
match elevatedValue1, elevatedValue2 with
| Success v1, Success v2 -> Success (v1, v2
| Success _, Failure errors -> Failure errors
| Failure errors, Success _ -> Failure errors
Failure e1, Failure e2 -> Failure (e1 @ e2)
let bind f elevatedValue =
match elevatedValue with
| Success value ->
match f value with ->
| Success value -> Success value
| Failure e -> Failure e
| Failure e -> Failure e
由于有了merge,你可以驗證兩個輸入并(可能)合并錯誤。由于bind,你可以繼續計算并處理其余部分也可能失敗的事實。你可以把你的組成函式寫成:
let formatReport (unvalidatedLanguageName: string)
(unvalidatedReport: UnvalidatedReport) 。Validation<string> =
合并
(languageTranslatorFor unvalidatedLanguageName)
(reportFrom unvalidatedReport)
|> 系結 formatReportAsText
uj5u.com熱心網友回復:
由于formatReportAsText回傳一個經過驗證的字串(而不是一個普通的字串),你應該在你的計算運算式的末尾使用return!而不是return:
return! formatReportAsText translator report
這就相當于:
let! value = formatReportAsText translator report // value 是一個string。
回傳 value value
如果我對你的代碼理解正確,那么計算運算式的型別將是Validation<string>而不是Validation<Validation<string>>。
注意,你需要在你的構建器上有一個ReturnFrom方法來使return!發揮作用:
member __.ReturnFrom(value) = value
詳見本頁面。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/311779.html
標籤:
下一篇:檢查字串是否不包含數值
