如何在 F# 中声明只有一个 Literal 属性的多个 Literals?
How to declare multiple Literals with only one Literal attribute in 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"
我正在尝试找到一种优雅的方式来为符号分配键,而无需执行以下操作。
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"