F# 将用户定义类型强制转换回元组
我是新来的。我正在使用一个包含元组的自定义类型F# 将用户定义类型强制转换回元组,f#,f#-data,F#,F# Data,我是新来的。我正在使用一个包含元组的自定义类型 type myType = | obj1 of int * int | obj2 of string * string 现在我有了一个函数,它产生了这个myType type Response = XmlProvider<"""<Result><ns7:value>Item 1</ns7:value>`<ns7:status>1</ns7:
type myType =
| obj1 of int * int
| obj2 of string * string
现在我有了一个函数,它产生了这个myType
type Response = XmlProvider<"""<Result><ns7:value>Item 1</ns7:value>`<ns7:status>1</ns7:status></Result>""", Global=true>`
let comparison (a:Response.Result) (b::Response.Result) = seq {
if a.Status <> b.Status then
yield Status(a.Value, a.Status, b.Status)
}
let a = """<Result><ns7:value>Item 1</ns7:value>`<ns7:status>1</ns7:status></Result>"""
let b = """<Result><ns7:value>Item 1</ns7:value>`<ns7:status>1</ns7:status></Result>"""
let compareResults = comparison a b |> Seq.toArray
我的问题是,当遍历比较结果
时,如何返回tupleobj1
和obj2
。目前我得到的只是myType
的对象。有没有办法将其转换回元组
更新
module Script.File1
开放系统
打开FSharp.Data
打开HttpClient
类型myType=
|字符串*int*int的Obj1
|字符串*字符串的Obj2
类型响应=XmlProvider
让比较(a:Response.Result)(b:Response.Result)=seq{
如果a.状态b.状态,则
产量Obj1(a.值、a.状态、b.状态)
}
设a=Response.Parse(““第11项”)
设b=Response.Parse(““第11项”)
让compareResults=比较a b |>Seq.toArray
让我们跑()=
对于c,比较结果如何
printfn“-%O”c
假设您有类似的内容(从一个简化的可编译示例开始):
现在,demo
是一系列的MyType
值,它们恰好都是Obj1
。您可以在值上进行模式匹配,但需要涵盖这两种情况,因为编译器不知道序列中的所有值都是allObj1
:
for d in demo do
match d with
| Obj1(i1, i2) -> printfn "%d %d" i1 i2
| _ -> failwith "Should not happen"
如果要避免这种情况,可以只生成一对整数,这样demo
的类型就是seq
。然后,您可以轻松地对其进行迭代,或者在需要时将其包装到Obj1
中
或者,您可以更改类型定义,使值是一个元组(用额外的括号括起来),而不仅仅是两个元素:
type MyType =
| Obj1 of (int * int)
| Obj2 of (string * string)
现在,您可以更轻松地传递int*int
值。例如:
let demo = seq {
for i in 0 .. 9 do
yield i, i }
// Turn sequence of tuples into `MyType`
let objs = Seq.map Obj1 demo
// Iterate over a sequence of tuples
for i1, i2 in demo do
printfn "%d %d" i1 i2
您问题中的代码类型不正确-您的
比较
函数中的a
和b
是什么,以及屈服状态(…)
中的状态
构造函数是什么。如果没有这些,就很难看到你在问什么。@mjosh获取值有多种方法,但是,如上所述,你的代码太抽象,无法给出具体的解决方案。从有区别的并集中获取值的最常用方法是模式匹配。你可以在中看到它的作用。它没有编译。@BentTranberg说了什么。您需要首先修复编译时错误(使obj1
和obj2
大写,修复无效的XML并定义状态
)。@BentTranberg检查更新
type MyType =
| Obj1 of (int * int)
| Obj2 of (string * string)
let demo = seq {
for i in 0 .. 9 do
yield i, i }
// Turn sequence of tuples into `MyType`
let objs = Seq.map Obj1 demo
// Iterate over a sequence of tuples
for i1, i2 in demo do
printfn "%d %d" i1 i2