Reputation: 1459
Below example is a snippet i took from "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
What i don't understand is the first pattern. How does the pattern-match successfully match the last three numbers from the list. Couldn't get my head around it.
Upvotes: 0
Views: 96
Reputation: 258
findSequence
a recursive function. Meaning it will look for a list of exactly 3 numbers, then a list of [1;2;3;...], then if both matches fail it will cons the list and recurse over the tail. In other words, it will keep popping elements off the head of the list, printing to the console every time it finds [1;2;3;...] until all that's left is the last 3 elements. The lines you're looking for that achieve this are:
| head :: tail -> findSequence tail
and
| 1 :: 2 :: 3 :: tail ->
printfn "Found sequence 1, 2, 3 within the list"
findSequence tail
Upvotes: 3