这种模式匹配如何工作?

时间:2014-08-15 08:12:06

标签: f#

以下示例是我从“F#Succinctly by Robert Pickering”中摘录的片段。

let rec findSequence l =
    match l with
    | [x; y; z] ->
        printfn "Last 3 numbers in the list were %i %i %i"
        x y z
    | 1 :: 2 :: 3 :: tail ->
        printfn "Found sequence 1, 2, 3 within the list"
        findSequence tail
    | head :: tail -> findSequence tail
    | [] -> ()

let testSequence = [1; 2; 3; 4; 5; 6; 7; 8; 9; 8; 7; 6; 5; 4; 3; 2; 1]

findSequence testSequence

我不明白的是第一种模式。模式匹配如何成功匹配列表中的最后三个数字。无法理解它。

1 个答案:

答案 0 :(得分:3)

findSequence一个递归函数。这意味着它将查找正好3个数字的列表,然后是[1; 2; 3; ...]的列表,然后如果两个匹配都失败,它将占据列表并递归尾部。换句话说,它会使弹出元素从列表的头部开始,每次找到[1; 2; 3; ...]时都会打印到控制台,直到剩下的所有元素都是最后3个元素。您正在寻找实现此目的的行是:

| head :: tail -> findSequence tail

| 1 :: 2 :: 3 :: tail -> printfn "Found sequence 1, 2, 3 within the list" findSequence tail