F#: Not understanding match .. with

后端 未结 1 1736
迷失自我
迷失自我 2020-12-12 02:00

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

相关标签:
1条回答
  • 2020-12-12 02:58

    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
    

    will print the value of someInt. It's the equivalent of let n = someInt; printfn "%d" n.

    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. 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
    
    0 讨论(0)
提交回复
热议问题