类型不匹配与模式匹配

dem*_*mas 4 f#

我有一个工作正常的代码:

let rec calculate s l acc =
    if length s = 0 then
        acc
    else
        if first s = l then
            calculate (rest s) l (acc+1)
        else
            calculate (rest s) (first s) acc
Run Code Online (Sandbox Code Playgroud)

我想用模式匹配重写它:

let rec calculate s l acc =
    function
    | _, _, _ when length s = 0 -> acc
    | _, _, _ when first s = l  -> calculate (rest s) l (acc+1)
    | _, _, _                   -> calculate (rest s) (first s) acc
Run Code Online (Sandbox Code Playgroud)

但是最后一个函数返回错误信息:

  | _, _, _ when first s = l  -> calculate (rest s) l (acc+1)   -----------------------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

/ Users/demas/temporary/stdin(512,36):错误FS0001:类型不匹配.期待'a但给定'b*'c*'d - >'a当统一''a'和''b*'c*'d - >'a'时,结果类型将是无限的

为什么?

Pet*_*etr 6

关键字function意味着函数的最后一个(隐式)参数calculate应该是包含3个元素的元组,因为你匹配_,_,_你可以将它重写为:

let rec calculate s l acc =
    match s, l, acc with
    | _, _, _ when length s = 0 -> acc
    | _, _, _ when first s = l  -> calculate (rest s) l (acc+1)
    | _, _, _                   -> calculate (rest s) (first s) acc
Run Code Online (Sandbox Code Playgroud)

你也可以使模式匹配更清晰地重写它:

let rec calculate s l acc =
    match (length s), (first s = l) with
    | 0, _    -> acc
    | _, true -> calculate (rest s) l (acc+1)
    | _, _    -> calculate (rest s) (first s) acc
Run Code Online (Sandbox Code Playgroud)