具有匹配模式错误的F#递归函数

时间:2020-10-10 12:14:58

标签: recursion f# pattern-matching syntax-error

我具有以下函数,该函数采用实数并计算其连续分数。 但是,我尝试使用match进行匹配,但是我不知道它是否可行,因为我需要进行以下检查 b < 0.0000000001,但是我不知道如果不使用if语句仅使用match怎么办?我需要能够利用<运算符

let rec floatfrac (x : float) : int list = 
    let a = int x
    let b = x - (float a)
    match b with
    | b < 0.0000000001 -> [] // error here because wrong syntax
    | _ -> (floatfrac (1.0 / b ))

printfn "%A" (floatfrac 3.14)

错误FS0010:模式中意外的浮点文字。预期的中缀运算符,引号或其他标记。

1 个答案:

答案 0 :(得分:4)

您可以在match语句中使用警戒线-在此处可以提供其他谓词,以实现由case模式本身未捕获的值:

let rec floatfrac (x : float) : int list = 
    let a = int x
    let b = x - (float a)
    match b with
    | _ when b < 0.0000000001 -> [] 
    | _ -> (floatfrac (1.0 / b ))

但是正如您从两种情况都使用通配符的事实可以看到的那样,当简单的if可以使用通配符时,首先使用匹配是没有意义的

if b < 0.0000000001 then 
    [] 
else 
    floatfrac (1.0 / b)
相关问题