问题
I am pretty new to the language F#, let alone functional programming, and I am having trouble implementing a Map data structure. The C# type equivalent of this Map would be:
var map = new Dictionary<int, Dictionary<int, Tuple<char, Tuple<int, int>[]>[]>>();
I've tried to implement this myself and searching online, but my inexperience with the language is letting me down.
Is anyone able to show me:
- An immutable implementation of this structure
- A mutable implementation
回答1:
For example like this:
let t1 = (2,3)
let t2 = ("a",t1)
let m1 = Map([1,t2])
let m2 = Map([2,m1])
The signature of this is:
val it : Map<int,Map<int,(string * (int * int))>> = map [(2, map [(1, ("a", (2, 3)))])]
This is using lists not array.
For the mutable part you already show the implementation. Just use
System.Collections.Generic.Dictionary
Not sure but maybe this is helpful for you: F# map to C# Dictionary
回答2:
The mere translation is pretty straightforward:
Dictionary
either becomesMap
(if you want an immutable structure) or stays as it is (if you want mutability)Tuple<a, b>
becomesa * b
in the type declaration, and(x, y)
in the variable usage.
Hence, if we go with immutability, we get:
Map<int, Map<int, (string * (int * int)[])[]>>
But that's, quite frankly, unreadable. Fortunately, F# has the perfect solution for this: type abbreviations.
That complex type can be decomposed into a bunch of aliases, or abbreviations, which express the problem domain more clearly to a human reader. For example, you could have:
type Cell = int * int
type Zone = Cell []
type Battleship = string * Zone
type Flotilla = Battleship []
type TaskForce = Map<int, Flotilla>
type Fleet = TaskForce []
type NavalTheater = Map<int, Fleet>
which is the exact same type as above, but it's a lot more readable, for most use cases. And it has zero overhead, as the abbreviations will be simply replaced with the native types during compilation.
来源:https://stackoverflow.com/questions/36393127/converting-complex-map-data-structure-to-f