如何在 F# 中声明只有一个文本属性的多个文本?



我正在尝试找到一种优雅的方式来为符号分配键,而不必执行如下所示的操作。

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"

相关内容

  • 没有找到相关文章

最新更新