如何从泛型中检索值?
具体来说,我正在尝试以下操作:
// Test
let result = Validate goodInput;;
// How to access record??
let request = getRequest result
这是代码:
type Result<'TSuccess,'TFailure> =
| Success of 'TSuccess
| Failure of 'TFailure
let bind nextFunction lastFunctionResult =
match lastFunctionResult with
| Success input -> nextFunction input
| Failure f -> Failure f
type Request = {name:string; email:string}
let validate1 input =
if input.name = "" then Failure "Name must not be blank"
else Success input
let validate2 input =
if input.name.Length > 50 then Failure "Name must not be longer than 50 chars"
else Success input
let validate3 input =
if input.email = "" then Failure "Email must not be blank"
else Success input;;
let Validate =
validate1
>> bind validate2
>> bind validate3;;
// Setup
let goodInput = {name="Alice"; email="[email protected] /cdn-cgi/l/email-protection"}
let badInput = {name=""; email="[email protected] /cdn-cgi/l/email-protection"};;
// I have no clue how to do this...
let getRequest = function
| "Alice", "[email protected] /cdn-cgi/l/email-protection" -> {name="Scott"; email="[email protected] /cdn-cgi/l/email-protection"}
| _ -> {name="none"; email="none"}
// Test
let result = Validate goodInput;;
// How to access record??
let request = getRequest result
printfn "%A" result
您的意思是如何从结果类型中提取记录?通过模式匹配,这就是您已经在做的事情bind
.
let getRequest result =
match result with
| Success input -> input
| Failure msg -> failwithf "Invalid input: %s" msg
let result = Validate goodInput
let record = getRequest result
这将返回记录或引发异常。一旦你有了自己的想法,你将如何处理成功和失败的案例Result
- 这可能会引发异常,或将其转变为选项,或记录消息并返回默认值等。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)