14 people like it.

Eliminating type annotations with single case Active Patterns

When passing objects as arguments to F# functions, it is almost certain that a type annotation will be required. This may generate long and noisy code at times, but thankfully we can use active patterns to mitigate this annoyance.

1: 
2: 
3: 
4: 
5: 
open System.Collections.Generic

let (|Dict|) (d : Dictionary<_,_>) = d

let tryFind (Dict d) k = if d.ContainsKey k then Some <| d.[k] else None
namespace System
namespace System.Collections
namespace System.Collections.Generic
val d : Dictionary<'a,'b>
Multiple items
type Dictionary<'TKey,'TValue> =
  new : unit -> Dictionary<'TKey, 'TValue> + 5 overloads
  member Add : key:'TKey * value:'TValue -> unit
  member Clear : unit -> unit
  member Comparer : IEqualityComparer<'TKey>
  member ContainsKey : key:'TKey -> bool
  member ContainsValue : value:'TValue -> bool
  member Count : int
  member GetEnumerator : unit -> Enumerator<'TKey, 'TValue>
  member GetObjectData : info:SerializationInfo * context:StreamingContext -> unit
  member Item : 'TKey -> 'TValue with get, set
  ...
  nested type Enumerator
  nested type KeyCollection
  nested type ValueCollection

Full name: System.Collections.Generic.Dictionary<_,_>

--------------------
Dictionary() : unit
Dictionary(capacity: int) : unit
Dictionary(comparer: IEqualityComparer<'TKey>) : unit
Dictionary(dictionary: IDictionary<'TKey,'TValue>) : unit
Dictionary(capacity: int, comparer: IEqualityComparer<'TKey>) : unit
Dictionary(dictionary: IDictionary<'TKey,'TValue>, comparer: IEqualityComparer<'TKey>) : unit
val tryFind : Dictionary<'a,'b> -> k:'a -> 'b option

Full name: Script.tryFind
active recognizer Dict: Dictionary<'a,'b> -> Dictionary<'a,'b>

Full name: Script.( |Dict| )
val k : 'a
union case Option.Some: Value: 'T -> Option<'T>
union case Option.None: Option<'T>
Raw view Test code New version

More information

Link:http://fssnip.net/cP
Posted:12 years ago
Author:Eirik Tsarpalis
Tags: active patterns , type annotations