This project is read-only.
Lists and Pattern Matching

Category:
Lists, Tuples and Options
Description: This sample shows simple uses of lists and functions that pattern match on them.
Code:
let ListSample1() =
let data = [1;2;3;4]
printfn "data = \n%A" data
printfn "List.head data = %d" (List.head data)
printfn "List.tail data = \n%A" (List.tail data)
printfn "List.length data = %d" (List.length data)
let consume data =
match data with
| 1::rest -> printfn "matched a 1"; rest
| 2::3::rest -> printfn "matched a 2 and 3"; rest
| [4] -> printfn "matched a 4"; []
| _ -> printfn "unexpected!"; []
let data = consume data
let data = consume data
let data = consume data
printfn "At end of list? %b" (data = [])

Execution Result:
data = 
[1; 2; 3; 4]
List.head data = 1
List.tail data =
[2; 3; 4]
List.length data = 4
matched a 1
matched a 2 and 3
matched a 4
At end of list? true

Last edited Sep 14, 2011 at 3:49 AM by ttliu2000, version 1

Comments

No comments yet.