11

我在 Haskell 编程语言中使用了Scrap Your Boilerplate和 Uniplate 库,我发现这种形式的泛型编程在可区分联合上非常有用。f# 编程语言中是否有等效的库?

4

1 回答 1

11

从来没听说过; 如果没有语言/编译器内置的支持,我希望唯一的选择是基于反射的版本。(我不知道Uniplate是如何实现的——你呢?)

这是基于原始演示文稿中的示例的基于反射的版本的代码。我没有深入考虑过它的局限性,但是写起来比我想象的要简单得多。

type Company = C of Dept list
and Dept = D of Name * Manager * SubUnit list
and SubUnit = | PU of Employee | DU of Dept
and Employee = E of Person * Salary
and Person = P of Name * Address
and Salary = S of float
and Manager = Employee
and Name = string
and Address = string

let data = C [D("Research",E(P("Fred","123 Rose"),S 10.0),
                  [PU(E(P("Bill","15 Oak"),S 5.0))])]
printfn "%A" data

open Microsoft.FSharp.Reflection 
let everywhere<'a,'b>(f:'a->'a, src:'b) =   // '
    let ft = typeof<'a>             // '
    let rec traverse (o:obj) =
        let ot = o.GetType()
        if ft = ot then
            f (o :?> 'a) |> box    // '
        elif FSharpType.IsUnion(ot) then
            let info,vals = FSharpValue.GetUnionFields(o, ot)
            FSharpValue.MakeUnion(info, vals |> Array.map traverse)
        else 
            o
    traverse src :?> 'b       // '

let incS (S x) = S(x+1.0) 

let newData = everywhere(incS, data)
printfn "%A" newData

The everywhere function traverses the entire structure of an arbitrary DU and applies the function f to each node that is the type that f works on, leaving all other nodes as-is.

于 2010-08-29T21:52:34.983 回答