f# - 从联合案例中提取值(value)

标签 f#

在 Fsharp 应用程序中,我定义了几个联合案例类型为

type A = A of String
type B = B of String
type C = C of String

我想定义一个函数来从联合案例实例中提取值。
let getValue( ctor: String-> 'a) = 
   ...implementation here

反正有没有完成这样的任务?
谢谢。

最佳答案

假设您有:

type A = A of string
type B = B of string
type C = C of string

let a = A "hello"
let b = B "world"
let c = C "!"

有很多方法可以提取这些值,这里有一些:

个人拆包机
let getValueA (A v) = v
let getValueB (B v) = v
let getValueC (C v) = v

let valueOfA = getValueA a
let valueOfB = getValueB b
let valueOfC = getValueC c

方法重载
type T =
    static member getValue (A v) = v
    static member getValue (B v) = v
    static member getValue (C v) = v

let valueOfA = T.getValue a
let valueOfB = T.getValue b
let valueOfC = T.getValue c

函数重载
type GetValue = GetValue with
    static member ($) (GetValue, (A v)) = v
    static member ($) (GetValue, (B v)) = v
    static member ($) (GetValue, (C v)) = v

let inline getValue x : string = GetValue $ x

let valueOfA = getValue a
let valueOfB = getValue b
let valueOfC = getValue c

反射(reflection)
open Microsoft.FSharp.Reflection
let getValue a =  
    FSharpValue.GetUnionFields (a, a.GetType())
        |> snd
        |> Seq.head
        :?> string

let valueOfA = getValue a
let valueOfB = getValue b
let valueOfC = getValue c

重新设计您的 DU
type A = A
type B = B
type C = C

type MyDU<'a> = MyDU of 'a * string

let a = MyDU (A, "hello")
let b = MyDU (B, "world")
let c = MyDU (C, "!"    )

let getValue (MyDU (_, v)) = v

let valueOfA = getValue a
let valueOfB = getValue b

重新设计接口(interface)
type IWrapped<'a> =
    abstract getValue: 'a

type A = A of string with interface IWrapped<string> with member t.getValue = let (A x) = t in x        
type B = B of string with interface IWrapped<string> with member t.getValue = let (B x) = t in x
type C = C of string with interface IWrapped<string> with member t.getValue = let (C x) = t in x

let valueOfA = (a :> IWrapped<string>).getValue

关于f# - 从联合案例中提取值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24217268/

相关文章:

c# - .NET 多目标与 .NET Standard 和可移植库 MSBuild 15

recursion - 具有递归函数的 Stackoverflow

F# 电源问题,它接受两个参数都是 bigint

.net - 列表、数组或其他什么?

types - 在学习 F# 时,为什么建议在字段中而不是在赋值时指定类型?

recursion - F# : Writing a function that builds a list of tuples recursively and change a mutable variable

haskell - 从 OO 到 10,000 英尺的函数式编程

c# - 加载包含作为通配符的项的 .NET 项目

.net - F# System.Random 重复值

c# - 设计或代码模式以从函数返回多个可选值