Dicts
This F# library provides:
A dedicated
Dict<'T>
type. It is a thin wrapper aroundDictionary<'T>
with more functionality and nicer Error messages.-
A
DefaultDict<'T>
type. It works like Python's' defaultdict.
By providing a default function in the constructor it will always return a value for any key. Extension methods for working with the
IDictionary<'T>
interface.
It also works in JS and TS with Fable.
This library was designed for use with F# scripting.
Functions and methods never return null.
Only functions starting with try...
will return an F# Option.
Otherwise when a function fails on invalid input it will throw a descriptive exception.
I was always annoyed that a KeyNotFoundExceptions does not include the actual bad key nor a pretty printed dictionary.
This library fixes that in iDictionary.Get
, iDictionary.Set
and other item access functions.
Example
#r "nuget: Dicts"
open Dicts
let dd = DefaultDict<string,int>(fun _ -> ref 99)
incr dd.["A"] // since dd.["A"] does not exist it will be created with the default value 99, and then incremented to 100
incr dd.["A"] // now it exists and will be incremented to 101
dd.["A"].Value = 101 // true
Full API Documentation
Tests
All Tests run in both javascript and dotnet. Successful Fable compilation to typescript is verified too. Go to the tests folder:
|
For testing with .NET using Expecto:
|
for JS testing with Fable.Mocha and TS verification:
|
License
Changelog
see CHANGELOG.md
type DefaultDict<'K,'V (requires equality)> = new: defaultOfKeyFun: ('K -> 'V) -> DefaultDict<'K,'V> member Add: k: 'K * v: 'V -> unit member Clear: unit -> unit member ContainsKey: k: 'K -> bool member ContainsValue: v: 'V -> bool member DoesNotContainKey: key: 'K -> bool member Get: k: 'K -> 'V member Pop: k: 'K -> 'V member Remove: k: 'K -> bool member Set: key: 'K -> value: 'V -> unit ...
<summary> A Collections.Generic.Dictionary<'K,'V> with default Values that get created upon accessing a missing key. If accessing a non exiting key , the default function is called to create and set it. Inspired by the defaultdict in Python. If you need to provide a custom implementation of the default function depending on each key, then use the Dict<'K,'V> type and it's method <c>Dicts.getOrSetDefault func key</c>. </summary>
--------------------
new: defaultOfKeyFun: ('K -> 'V) -> DefaultDict<'K,'V>
val string: value: 'T -> string
--------------------
type string = System.String
val int: value: 'T -> int (requires member op_Explicit)
--------------------
type int = int32
--------------------
type int<'Measure> = int
val ref: value: 'T -> 'T ref
--------------------
type 'T ref = Ref<'T>