11 people like it.

Methods deconstruction via active patterns

We can use active patterns for methods deconstruction. It allow to hide some rough SRTP syntax.

1: 
2: 
3: 
4: 
5: 
6: 
7: 
8: 
9: 
let inline (|HasLength|) x = 
  fun () -> (^a: (member Length: int) x)

// `this` is optional here, just for demonstration `as` pattern
let inline length (HasLength f as this) = f()

// It works!
let foo = length [1; 2; 3]
let bar = length [|1; 2; 3|]
val x : 'a (requires member get_Length)
Multiple items
val int : value:'T -> int (requires member op_Explicit)

Full name: Microsoft.FSharp.Core.Operators.int

--------------------
type int = int32

Full name: Microsoft.FSharp.Core.int

--------------------
type int<'Measure> = int

Full name: Microsoft.FSharp.Core.int<_>
val length : 'a -> int (requires member get_Length)

Full name: Script.length
active recognizer HasLength: 'a -> unit -> int

Full name: Script.( |HasLength| )
val f : (unit -> int)
val this : 'a (requires member get_Length)
val foo : int

Full name: Script.foo
val bar : int

Full name: Script.bar
Next Version Raw view Test code New version

More information

Link:http://fssnip.net/7U0
Posted:7 years ago
Author:Evgeniy Andreev
Tags: #active patterns , #srtp