文字属性不起作用 [英] Literal Attribute not working

查看:48
本文介绍了文字属性不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读完克里斯对 F#-公共文字的回答以及 http://blogs.msdn .com/b/chrsmith/archive/2008/10/03/f-zen-the-literal-attribute.aspx 我不明白为什么以下各项不起作用:

After reading Chris' answer to F# - public literal and the blog post at http://blogs.msdn.com/b/chrsmith/archive/2008/10/03/f-zen-the-literal-attribute.aspx I don't get why the following is not working:

[<Literal>]
let one = 1

[<Literal>]
let two = 2

let trymatch x =
    match x with
    | one -> printfn "%A" one
    | two -> printfn "%A" two
    | _ -> printfn "none"


trymatch 3

尽管我认为不应该,但它始终打印"3".我在这里看不到什么?

This keeps printing "3", although I think it shouldn't. What is it that I don't see here?

推荐答案

我认为文字必须为大写.以下工作正常:

I think that literals need to be Uppercase. The following works fine:

[<Literal>]
let One = 1
[<Literal>]
let Two = 2

let trymatch x =
    match x with
    | One -> printfn "%A" One
    | Two -> printfn "%A" Two
    | _ -> printfn "none"


trymatch 3

此外,如果您想要一个很好的通用解决方案而不使用文字,则可以定义一个参数化的活动模式,如下所示:

In addition, if you want a nice general solution for this without using literals, you can define a parameterized active pattern like this:

let (|Equals|_|) expected actual = 
  if actual = expected then Some() else None

然后写

let one = 1
let two = 2

let trymatch x =
    match x with
    | Equals one -> printfn "%A" one
    | Equals two -> printfn "%A" two
    | _ -> printfn "none"

这篇关于文字属性不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆