F#:不了解与..的匹配 [英] F#: Not understanding match .. with

查看:80
本文介绍了F#:不了解与..的匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在搞弄F#和寓言,并试图检验我的理解.为此,我尝试创建一个函数以给定一定的迭代次数来计算e.我想出的是

I'm messing around with F# and Fable, and trying to test my understanding. To do so, I tried creating a function to calculate e given a certain number of iterations. What I've come up with is

let eCalc n =
      let rec internalECalc ifact sum count =
          match count = n with
          | true -> sum
          | _ -> internalECalc (ifact / (float count)) (sum + ifact) (count+1)

      internalECalc 1.0 0.0 1

哪个可以正常工作,当调用时返回2.7182818284590455

Which works fine, returning 2.7182818284590455 when called with

eCalc 20

但是,如果我尝试使用的话,我认为是更正确的形式

However, if I try using, what I think is, the more correct form

let eCalc n =
      let rec internalECalc ifact sum count =
          match count with
          | n -> sum
          | _ -> internalECalc (ifact / (float count)) (sum + ifact) (count+1)

      internalECalc 1.0 0.0 1

我收到警告"[警告]此规则将永远不会被匹配(L5,10-L5,11)",并且返回值为0.(如果我交换"n"和"count",也会发生相同的情况在match语句中).我不能在match语句中使用'n'吗?有没有办法解决这个问题,所以我可以使用'n'?

I get a warning "[WARNING] This rule will never be matched (L5,10-L5,11)", and returned value of 0. (and the same thing happens if I swap 'n' and 'count' in the match statement). Is there a reason I can't use 'n' in the match statement? Is there a way around this so I can use 'n'?

谢谢

推荐答案

match语句中使用名称时,您将其与分配给该变量的值进行比较.您以为自己的方式.相反,您是分配该名称.即

When you use a name in a match statement, you're not checking it against the value assigned to that variable the way you think you are. You are instead assigning that name. I.e.,

match someInt with
| n -> printfn "%d" n

将打印someInt的值.相当于let n = someInt; printfn "%d" n.

您想要做的是使用when子句;在when子句中,您不是模式匹配,而是进行标准"检查.所以您想要的是:

What you wanted to do was use a when clause; inside a when clause, you're not pattern-matching, but doing a "standard" if check. So what you wanted was:

let eCalc n =
      let rec internalECalc ifact sum count =
          match count with
          | cnt when cnt = n -> sum
          | _ -> internalECalc (ifact / (float count)) (sum + ifact) (count+1)

      internalECalc 1.0 0.0 1

这有意义吗,还是您需要我进一步详细介绍?

Does that make sense, or do you need me to go into more detail?

P.S.在这种情况下,您的匹配函数看起来像"x when(涉及x的布尔条件)->案例1 | _->案例2",使用简单的if表达式可读性更高:

P.S. In a case like this one where your match function looks like "x when (boolean condition involving x) -> case 1 | _ -> case 2", it's quite a bit more readable to use a simple if expression:

let eCalc n =
      let rec internalECalc ifact sum count =
          if count = n then
              sum
          else
              internalECalc (ifact / (float count)) (sum + ifact) (count+1)

      internalECalc 1.0 0.0 1

这篇关于F#:不了解与..的匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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