简体   繁体   English

F#地图和不同的对象

[英]F# map and distinct objects

I have some nondescript but distinct objects (specifically, unnamed variables in logic expressions) that I want to put in a map that associates them with their values. 我有一些非描述性但截然不同的对象(特别是逻辑表达式中的未命名变量),我想放入一个映射中,以将它们与其值相关联。 As I understand it, map needs to distinguish objects by some ordered field, so I can't just have 据我了解,地图需要通过一些有序字段来区分对象,所以我不能只拥有

type Term =
...
| Var

as this would not allow different variables distinguishable from each other. 因为这将不允许将不同的变量区分开。 Instead I could presumably have 相反,我大概可以

type Term =
...
| Var of int64

and then have a new_var function that increments a global int64 counter and returns a new variable with the incremented value. 然后具有一个new_var函数,该函数将全局int64计数器递增,并返回具有递增值的新变量。 This seems slightly inelegant, but should work. 这似乎有些微不足道,但应该可以。

Is the global counter the recommended way to handle this, or is there a more idiomatic method? 建议使用全局计数器来处理此问题,还是有一种更惯用的方法?

It's not really a "map having to distinguish objects" thing - when you declare a type like this: 这实际上不是“必须区分对象的映射”的事情-当您声明这样的类型时:

type Term = 
    | Var

you have a type with a single valid value - Var . 您有一个具有单个有效值的类型Var If you're saying you want to have objects that are distinct - this is not what you want. 如果您要说的是要有不同的对象,那不是您想要的。 You can still use that type as a key in a map - not a particularly useful one though, since it will have at most a single element. 您仍然可以将这种类型用作地图中的键-尽管不是一个特别有用的键,因为它最多只有一个元素。

Using a counter is a good enough way to handle it. 使用计数器是处理它的一种好方法。 If you don't want a "global" one, you can roll it into a function using a ref cell to hold it: 如果您不希望使用“全局”函数,则可以使用ref单元将其滚动到一个函数中来保存它:

type Term = 
    | Var of int

let make = 
    let counter = ref 0
    fun () ->
        counter := !counter + 1
        Term.Var (!counter)

Or use GUIDs if you don't care about the values and want the counter out of the picture: 如果您不关心这些值并希望计数器不显示图片,则可以使用GUID:

 type Term = 
     | Var of System.Guid

 let make () = 
     Term.Var (System.Guid.NewGuid())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM