如何从复合泛型类型检索值? [英] How do I retrieve a value from a composite generic type?
本文介绍了如何从复合泛型类型检索值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从泛型中检索值?
具体来说,我正在尝试以下操作:
Specifically, I am attempting the following:
// 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="abc@abc.com"}
let badInput = {name=""; email="abc@abc.com"};;
// I have no clue how to do this...
let getRequest = function
| "Alice", "abc@abc.com" -> {name="Scott"; email="xyz@xyz.com"}
| _ -> {name="none"; email="none"}
// Test
let result = Validate goodInput;;
// How to access record??
let request = getRequest result
printfn "%A" result
推荐答案
您的意思是如何从结果类型中提取记录?通过模式匹配,这就是您在bind
中已经完成的工作.
You mean how do you extract the record out of your result type? Through pattern matching, that's what you're already doing in 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
的成功案例和失败案例-可能引发异常,或者将其转换为选项,或者记录消息并返回默认值等.
This will return the record or throw an exception. Up to you how you handle the success and failure cases once you have your Result
- that could be throwing an exception, or turning it into option, or logging the message and returning a default etc.
这篇关于如何从复合泛型类型检索值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文