gpt4 book ai didi

f# - 如何在 F# 中对可区分联合的子集进行建模?

转载 作者:行者123 更新时间:2023-12-03 15:44:03 25 4
gpt4 key购买 nike

我想要一个东西(人、物体、任何东西)有能力(跳跃、奔跑等)。我希望有些东西只有某些能力。这些是我目前的类型:

type Ability =
| Jump
| Stay
| Run
| Walk

type Person = {
abilities : Ability Set // OK, since a person should be able to do all of the above
}

type InanimateObject = {
abilities : Ability Set // Not OK, it should only be able to "Stay"
}

type ThingWithAbilities =
| Person of Person
| InanimateObject of InanimateObject

我希望我的 API 的调用者能够请求 ThingWithAbilities具有特定的能力。示例:给我 ThingWithAbilities 的所有对象具有“跳跃”能力。我怎样才能以一种好的方式对此进行建模?我想让它无法创建 InanimateObject在代码中具有“跳跃”的能力。

最佳答案

如果您想以类型安全的方式执行此操作,则需要为不同的能力集定义不同的类型:

type InanimateAbility =
| Stay

type AnimateAbility =
| Jump
| Run
| Walk

type Ability =
| Inanimate of InanimateAbility
| Animate of AnimateAbility

type Person = {
abilities : Ability Set
}

type InanimateObject = {
abilities : InanimateAbility Set
}

在这里, InanimateAbility是一种只有无生命物体才有的能力类型,并且 AnimateAbility是动画对象独有的能力类型。 Ability结合了这两者,代表了任何一种能力。 Person然后可以有一套 Abilitiy值,但您可以限制 InanimateObject 的能力来一套 InanimateAbility值。

只要您没有太多组合,这就可以正常工作 - 如果您有四种不同类型的对象,具有不同的能力子集,那么它可能会变得困惑。在这种情况下,您可能只使用一种类型进行运行时检查,以确保您只为每个对象分配允许的能力。

关于f# - 如何在 F# 中对可区分联合的子集进行建模?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58077481/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com