F #: Misunderstanding the match .. with

I've been messing around with F # and Fable and trying to test my understanding. For this, I tried to create a function to calculate e with a certain number of iterations. What I came 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

      

Which works fine, returning 2.7182818284590455 when called with

eCalc 20

      

However, if I try to use what I think is a 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

      

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

thank

+2


source to share


1 answer


When you use a name in a statement match

, you do not check against the value assigned to that variable as you think. Instead, you assign this name. I.e.

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

      

will print the value someInt

. This is equivalent let n = someInt; printfn "%d" n

.

What you wanted to do was use a sentence when

; inside a clause, when

you don't bind to a template, but you do "standard" validation. So what you wanted:



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 this make sense, or do you need me to go into more detail?

PS In a case like this, where your match function looks like "x when (boolean condition associated with x) -> case 1 | _ -> case 2", it's pretty readable to use a simple expression if

:

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

      

+10


source







All Articles