如何从复合泛型类型检索值?

编程入门 行业动态 更新时间:2024-10-23 11:25:40
本文介绍了如何从复合泛型类型检索值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何从泛型中检索值?

具体来说,我正在尝试以下操作:

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"} let badInput = {name=""; email="abc@abc"};; // I have no clue how to do this... let getRequest = function | "Alice", "abc@abc" -> {name="Scott"; email="xyz@xyz"} | _ -> {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.

更多推荐

如何从复合泛型类型检索值?

本文发布于:2023-10-24 17:02:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524505.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!