Converting complex Map data structure to F#

牧云@^-^@ 提交于 2019-12-24 18:12:51

问题


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:

  1. An immutable implementation of this structure
  2. 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 becomes Map (if you want an immutable structure) or stays as it is (if you want mutability)
  • Tuple<a, b> becomes a * 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!