Skip to content

Commit

Permalink
refactor VariantUnwrap into VariantTag
Browse files Browse the repository at this point in the history
  • Loading branch information
konnov committed Jul 7, 2022
1 parent 337822e commit 6797f51
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 17 deletions.
18 changes: 6 additions & 12 deletions src/tla/Variants.tla
Original file line number Diff line number Diff line change
Expand Up @@ -41,24 +41,18 @@ VariantFilter(__tagName, __S) ==
{ __d \in { __e \in __S: __e.tag = __tagName }: __d.value }

(**
* In cases where `variant` allows for one value,
* extract the associated value and return it.
* The type checker must enforce that `variant` allows for one option.
* Get the tag name that is associated with a variant.
*
* @param `tagValue` the tag attached to the variant
* @param `variant` a variant that is constructed with `Variant(...)`
* @return the value extracted from the variant
* @return the tag name associated with a variant
*
* Its type could look like follows:
* Its type is as follows:
*
* (Str, Tag(a)) => a
* Variant(a) => Str
*)
VariantUnwrap(__tagName, __variant) ==
VariantTag(__variant) ==
\* default untyped implementation
IF __variant.tag = __tagName
THEN __variant.value
ELSE \* trigger an error in TLC by choosing a non-existent element
CHOOSE x \in { __variant }: x.tag = __tagName
__variant.tag

(**
* Return the value associated with the tag, when the tag equals to __tagName.
Expand Down
8 changes: 3 additions & 5 deletions test/tla/TestVariants.tla
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,8 @@ TestVariantFilter ==
\E v \in VariantFilter("B", { VarA, VarB }):
v.value = "hello"

TestVariantUnwrap ==
\* We could just pass "world", without wrapping it in a record.
\* But we want to see how it works with records too.
VariantUnwrap("C", VarC) = [ value |-> "world" ]
TestVariantTag ==
VariantTag(VarC) = "C"

TestVariantGetUnsafe ==
\* The unsafe version gives us only a type guarantee.
Expand All @@ -49,7 +47,7 @@ TestVariantGetOrElse ==
AllTests ==
/\ TestVariant
/\ TestVariantFilter
/\ TestVariantUnwrap
/\ TestVariantTag
/\ TestVariantGetUnsafe
/\ TestVariantGetOrElse

Expand Down

0 comments on commit 6797f51

Please sign in to comment.