我试图找到一种优雅的方式来为符号分配键,而不必像以下那样做。
let [<Literal>] North = ConsoleKey.UpArrow // etc.
我宁愿做这样的事情,只使用一个属性。有什么方法可以做到吗?
[<Literal>]
type Direction =
| North of ConsoleKey.UpArrow
| East of ConsoleKey.RightArrow
| South of ConsoleKey.DownArrow
| West of ConsoleKey.LeftArrow
假设您的目标是在模式匹配中使用这些,这是一种方法:
// Use a type alias to shorten the name for ConsoleKey
type Key = ConsoleKey
// Create a general purpose active pattern that simply tests for equality
let (|Is|_|) a b = if a = b then Some () else None
// This is how you would use it
let describeMovement key =
match key with
| Is Key.UpArrow -> "up"
| Is Key.RightArrow -> "right"
| Is Key.DownArrow -> "down"
| Is Key.LeftArrow -> "left"
| _ -> "invalid"