项目作者: eiriktsarpalis

项目描述 :
Practical generic programming for F#
高级语言: F#
项目地址: git://github.com/eiriktsarpalis/TypeShape.git
创建时间: 2016-07-22T13:50:07Z
项目社区:https://github.com/eiriktsarpalis/TypeShape

开源协议:MIT License

下载


TypeShape Build & Tests NuGet Badge

TypeShape is a small, extensible F# library for practical datatype-generic programming.
Borrowing from ideas used in the FsPickler implementation,
it uses a combination of reflection, active patterns and F# object expressions to minimize the
amount of reflection required by the user in such applications.

TypeShape permits definition of programs that act on specific algebrae of types.
The library uses reflection to derive the algebraic structure of a given
System.Type instance and then applies a variant of the visitor pattern
to provide relevant type information per shape.

TypeShape can provide significant performance improvements compared to equivalent reflection-based approaches.
See the performance page for more details and benchmarks.

Please see my article and slides for a more thorough introduction to the concept.

Installing

To incorporate TypeShape in your project place the following line in your
paket.dependencies file:

  1. github eiriktsarpalis/TypeShape:10.0.0 src/TypeShape/TypeShape.fs

and in paket.references:

  1. File: TypeShape.fs TypeShape

TypeShape is also available on NuGet Badge

Example: Implementing a value printer

  1. open System
  2. open TypeShape.Core
  3. let rec mkPrinter<'T> () : 'T -> string =
  4. let wrap(p : 'a -> string) = unbox<'T -> string> p
  5. match shapeof<'T> with
  6. | Shape.Unit -> wrap(fun () -> "()")
  7. | Shape.Bool -> wrap(sprintf "%b")
  8. | Shape.Byte -> wrap(fun (b:byte) -> sprintf "%duy" b)
  9. | Shape.Int32 -> wrap(sprintf "%d")
  10. | Shape.Int64 -> wrap(fun (b:int64) -> sprintf "%dL" b)
  11. | Shape.String -> wrap(sprintf "\"%s\"")
  12. | Shape.FSharpOption s ->
  13. s.Element.Accept {
  14. new ITypeVisitor<'T -> string> with
  15. member _.Visit<'a> () =
  16. let tp = mkPrinter<'a>()
  17. wrap(function None -> "None" | Some t -> sprintf "Some (%s)" (tp t))
  18. }
  19. | Shape.FSharpList s ->
  20. s.Element.Accept {
  21. new ITypeVisitor<'T -> string> with
  22. member _.Visit<'a> () =
  23. let tp = mkPrinter<'a>()
  24. wrap(fun ts -> ts |> List.map tp |> String.concat "; " |> sprintf "[%s]")
  25. }
  26. | Shape.Array s when s.Rank = 1 ->
  27. s.Element.Accept {
  28. new ITypeVisitor<'T -> string> with
  29. member _.Visit<'a> () =
  30. let tp = mkPrinter<'a> ()
  31. wrap(fun ts -> ts |> Array.map tp |> String.concat "; " |> sprintf "[|%s|]")
  32. }
  33. | Shape.Tuple (:? ShapeTuple<'T> as shape) ->
  34. let mkElemPrinter (shape : IShapeMember<'T>) =
  35. shape.Accept { new IMemberVisitor<'T, 'T -> string> with
  36. member _.Visit (shape : ShapeMember<'DeclaringType, 'Field>) =
  37. let fieldPrinter = mkPrinter<'Field>()
  38. fieldPrinter << shape.Get }
  39. let elemPrinters : ('T -> string) [] = shape.Elements |> Array.map mkElemPrinter
  40. fun (r:'T) ->
  41. elemPrinters
  42. |> Seq.map (fun ep -> ep r)
  43. |> String.concat ", "
  44. |> sprintf "(%s)"
  45. | Shape.FSharpSet s ->
  46. s.Accept {
  47. new IFSharpSetVisitor<'T -> string> with
  48. member _.Visit<'a when 'a : comparison> () =
  49. let tp = mkPrinter<'a>()
  50. wrap(fun (s:Set<'a>) -> s |> Seq.map tp |> String.concat "; " |> sprintf "set [%s]")
  51. }
  52. | _ -> failwithf "unsupported type '%O'" typeof<'T>
  53. let p = mkPrinter<int * bool option * string list * int []> ()
  54. p (42, Some false, ["string"], [|1;2;3;4;5|])
  55. // val it : string = "(42, Some (false), ["string"], [|1; 2; 3; 4; 5|])"

Records, Unions and POCOs

TypeShape can be used to define generic programs that access fields of arbitrary types:
F# records, unions or POCOs. This is achieved using the IShapeMember abstraction:

  1. type IShapeMember<'DeclaringType, 'Field> =
  2. abstract Get : 'DeclaringType -> 'Field
  3. abstract Set : 'DeclaringType -> 'Field -> 'DeclaringType

An F# record then is just a list of member shapes, a union is a list of lists of member shapes.
Member shapes can optionally be configured to generate code at runtime for more performant Get and Set operations.
Member shapes come with quoted versions of the API for staged generic programming applications.

To make our pretty printer support these types, we first provide a pretty printer for members:

  1. let mkMemberPrinter (shape : IShapeMember<'DeclaringType>) =
  2. shape.Accept { new IMemberVisitor<'DeclaringType, 'DeclaringType -> string> with
  3. member _.Visit (shape : ShapeMember<'DeclaringType, 'Field>) =
  4. let fieldPrinter = mkPrinter<'Field>()
  5. fieldPrinter << shape.Get }

Then for F# records:

  1. match shapeof<'T> with
  2. | Shape.FSharpRecord (:? ShapeFSharpRecord<'T> as shape) ->
  3. let fieldPrinters : (string * ('T -> string)) [] =
  4. s.Fields |> Array.map (fun f -> f.Label, mkMemberPrinter f)
  5. fun (r:'T) ->
  6. fieldPrinters
  7. |> Seq.map (fun (label, fp) -> sprintf "%s = %s" label (fp r))
  8. |> String.concat "; "
  9. |> sprintf "{ %s }"

Similarly, we could also add support for arbitrary F# unions:

  1. match shapeof<'T> with
  2. | Shape.FSharpUnion (:? ShapeFSharpUnion<'T> as shape) ->
  3. let cases : ShapeFSharpUnionCase<'T> [] = shape.UnionCases // all union cases
  4. let mkUnionCasePrinter (case : ShapeFSharpUnionCase<'T>) =
  5. let fieldPrinters = case.Fields |> Array.map mkMemberPrinter
  6. fun (u:'T) ->
  7. fieldPrinters
  8. |> Seq.map (fun fp -> fp u)
  9. |> String.concat ", "
  10. |> sprintf "%s(%s)" case.CaseInfo.Name
  11. let casePrinters = cases |> Array.map mkUnionCasePrinter // generate printers for all union cases
  12. fun (u:'T) ->
  13. let tag : int = shape.GetTag u // get the underlying tag for the union case
  14. casePrinters.[tag] u

Similar active patterns exist for classes with settable properties and general POCOs.

Extensibility

TypeShape can be extended to incorporate new active patterns supporting arbitrary shapes.
Here’s an example
illustrating how TypeShape can be extended to support ISerializable shapes.

Additional examples

See the project samples folder for more implementations using TypeShape:

  • Printer.fs Pretty printer generator for common F# types.
  • Parser.fs Parser generator for common F# types using FParsec.
  • Equality-Comparer.fs Equality comparer generator for common F# types.
  • hashcode-staged.fs Staged generic hashcode generator.
  • Gmap There are set of gmap related functions within the TypeShape.Generic module in the Nuget package.

Using the Higher-Kinded Type API

As of TypeShape 8 it is possible to avail of a higher-kinded type flavour of the api,
which can be used to author fully type-safe programs for most common applications.
Please see my original article on the subject for background and motivation.

To use the new approach, we first need to specify which types we would like our generic program to support:

  1. open TypeShape.HKT
  2. type IMyTypesBuilder<'F> =
  3. inherit IBoolBuilder<'F>
  4. inherit IInt32Builder<'F>
  5. inherit IStringBuilder<'F>
  6. inherit IFSharpOptionBuilder<'F>
  7. inherit IFSharpListBuilder<'F>
  8. inherit ITuple2Builder<'F>

The interface MyTypeBuilder<'F> denotes a “higher-kinded” generic program builder
which supports combinations of boolean, integer, string, optional, list and pair types.

Next, we need to define how interface implementations are to be folded:

  1. let mkGenericProgram (builder : IMyTypesBuilder<'F>) =
  2. { new IGenericProgram<'F> with
  3. member this.Resolve<'a> () : App<'F, 'a> =
  4. match shapeof<'a> with
  5. | Fold.Bool builder r -> r
  6. | Fold.Int32 builder r -> r
  7. | Fold.String builder r -> r
  8. | Fold.Tuple2 builder this r -> r
  9. | Fold.FSharpOption builder this r -> r
  10. | Fold.FSharpList builder this r -> r
  11. | _ -> failwithf "I do not know how to fold type %O" typeof<'a> }

This piece of boilerplate composes built-in Fold.* active patterns,
which contain folding logic for the individual builders inherited by the interface.
Note that the order of composition can be significant (e.g. folding with FSharpOption before FSharpUnion).

Let’s now provide a pretty-printer implementation for our interface:

  1. // Higher-Kinded encoding
  2. type PrettyPrinter =
  3. static member Assign(_ : App<PrettyPrinter, 'a>, _ : 'a -> string) = ()
  4. // Implementing the interface
  5. let prettyPrinterBuilder =
  6. { new IMyTypesBuilder<PrettyPrinter> with
  7. member _.Bool () = HKT.pack (function false -> "false" | true -> "true")
  8. member _.Int32 () = HKT.pack (sprintf "%d")
  9. member _.String () = HKT.pack (sprintf "\"%s\"")
  10. member _.Option (HKT.Unpack elemPrinter) = HKT.pack(function None -> "None" | Some a -> sprintf "Some(%s)" (elemPrinter a))
  11. member _.Tuple2 (HKT.Unpack left) (HKT.Unpack right) = HKT.pack(fun (a,b) -> sprintf "(%s, %s)" (left a) (right b))
  12. member _.List (HKT.Unpack elemPrinter) = HKT.pack(Seq.map elemPrinter >> String.concat "; " >> sprintf "[%s]") }

Putting it all together gives us a working pretty-printer:

  1. let prettyPrint<'t> : 't -> string = (mkGenericProgram prettyPrinterBuilder).Resolve<'t> () |> HKT.unpack
  2. prettyPrint 42
  3. prettyPrint (Some false)
  4. prettyPrint (Some "test", [Some 42; None; Some -1])

Please check the samples/HKT folder for real-world examples of the above.

Projects using TypeShape