-4

実行時にリフレクションを使用して F# で新しい型 (たとえば、2 つの型のデカルト積) を作成する方法の例を教えてください。

アップデート

ファーストクラスの型を持つ言語を探しています。F# でできると言われました。F# をまだ学んでいないので、何も試しませんでした。どうやって作っているのか見たいだけです。

4

2 に答える 2

6

次の F# コードは、値の 2 つのシーケンス (例ではランクとスーツ) を取り、リフレクションを使用して実行時に動的に生成されたペア型を使用して、デカルト積をペア (カード) のシーケンスとして返します。

open System
open System.Reflection
open System.Reflection.Emit
open Microsoft.FSharp.Reflection

/// Creates a dynamic module via reflection
let createModule () =
    let name = Guid.NewGuid().ToString()
    let d = AppDomain.CurrentDomain
    let a = d.DefineDynamicAssembly(AssemblyName(name), AssemblyBuilderAccess.Run)
    a.DefineDynamicModule(name)
/// Creates a dynamic pair type using the specified x and y types
let createPairType (x:Type, y:Type) =
    let m = createModule()
    let t = m.DefineType("Pair", TypeAttributes.Public ||| TypeAttributes.Class)
    let x = t.DefineField(x.Name, x, FieldAttributes.Public)
    let y = t.DefineField(y.Name, y, FieldAttributes.Public)
    t.CreateType()
/// Creates a pair value using the specified pair type
let createPairValue (pairType:Type) (x:'X, y:'Y) =
    let instance = Activator.CreateInstance(pairType)
    pairType.GetField(typeof<'X>.Name).SetValue(instance, x)
    pairType.GetField(typeof<'Y>.Name).SetValue(instance, y)
    instance
/// Creates a cartesian product 
let createCartesianProduct (xs:'X seq, ys:'Y seq) =
    let pairType = createPairType (typeof<'X>,typeof<'Y>) 
    seq { for x in xs do for y in ys -> createPairValue pairType (x, y) }
/// Defines dynamic lookup operator for accessing a named field
let inline (?) (x:obj) name = x.GetType().GetField(name).GetValue(x)
/// Card suit discriminated union type
type Suit = Club | Diamond | Heart | Spade
/// Card rank discriminated union type 
type Rank = | One | Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten
            | Jack | Queen | King | Ace
/// Gets union case values
let getUnionValues<'T>() = 
    FSharpType.GetUnionCases(typeof<'T>) 
    |> Seq.map (fun x -> FSharpValue.MakeUnion(x,[||]) :?> 'T)
let ranks, suits = getUnionValues<Rank>(), getUnionValues<Suit>()
/// Sequence of dynamically generated pairs
let cards = createCartesianProduct (ranks, suits)
// Paste this into F# interactive to print the generated cards
for card in cards do printfn "%A %A" card?Rank card?Suit
于 2013-01-27T21:10:58.680 に答える
3

F#.NET Journalの私の (無料ではない) 記事Structural Typingから引用:

次の createType 関数は、指定された名前の新しい .NET アセンブリ、新しいモジュール、および新しいパブリック クラス タイプを作成します。

> let createType typeName =
    let name = System.Reflection.AssemblyName(Name="tmpAssembly")
    let run = System.Reflection.Emit.AssemblyBuilderAccess.Run
    let builder = System.Threading.Thread.GetDomain().DefineDynamicAssembly(name, run)
    let mdl = builder.DefineDynamicModule "tmpModule"
    let attrs = TypeAttributes.Public ||| TypeAttributes.Class
    mdl.DefineType(typeName, attrs);;
val createType : string -> TypeBuilder
于 2013-01-27T20:30:42.140 に答える