【F#学习】列表 List

F#中的列表list是不可变的一列数据。列表中的数据必须具有相同的数据类型。任何试图对列表进行修改的函数或者运算符,实际上都是构建了一个新的列表。

用如下方式来定义一个列表:

let empty = []
let singleValue = [5]
let threeValues = ["a"; "b"; "c"]

最普遍的向列表中添加元素的方式是通过cons运算符::

let twoToFour = [2; 3; 4]
let oneToFour = 1 :: twoToFour
// => [1; 2; 3; 4]

一个列表有一个head,剩下的内容都是tail,即:head为首个元素,tail为除开head的余下的列表。(这和 Haskell 是一致的)

List.head [1; 2; 3; 4; 5] // => 1
List.tail [1; 2; 3; 4; 5] // => [2; 3; 4; 5]

let describe list =
    match list with
    | [] -> "Empty list"
    | head::tail -> sprintf "Non-empty list with head: %d" head

describe []        // => "Empty list"
describe [1]       // => "Non-empty with head: 1"
describe [5; 7; 9] // => "Non-empty with head: 5"

在模式匹配中使用抛弃符_

let describe list =
    match list with
    | [] -> "Empty list"
    | [x] -> "List with one item"
    | [_; y] -> "List with two items (first item ignored)"
    | _ -> "List with many items (all items ignored)"

describe []        // => "Empty list"
describe [1]       // => "List with one item"
describe [5; 7]     // => "List with two items (first item ignored)"
describe [5; 7; 9] // => "List with many items (all items ignored)"
posted @ 2025-09-23 12:25  QMazon  阅读(9)  评论(0)    收藏  举报