类型不匹配与模式匹配

时间:2014-12-08 13:44:03

标签: 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

我想用模式匹配重写它:

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

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

  | _, _, _ when first s = l  -> calculate (rest s) l (acc+1)   -----------------------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     

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

为什么?

1 个答案:

答案 0 :(得分: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

此外,您可以使模式匹配更清晰地重写,如:

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