使用F#的List
创建一个list:
语法 | 描述 | 示例 |
[] | 空list | [] |
expr :: expr | 将一个项加入一个list | 1 :: [2; 3] |
[expr; ...; expr] | 列举项创建list | [1; 2; 3] |
[expr .. expr] | 连续的数字 | [1 .. 99] |
[ for x in list ... ] | 通过运算生成list(类似于Linq里的select) | [ for x in 1..99 -> x * x ] |
expr @ expr | 合并两个list | [1; 2] @ [3] |
操作示例:
let oddPrimes = [3; 5; 7; 11]
let morePrimes = [13; 17]
let primes = 2 :: (oddPrimes @ morePrimes)
val primes : int list = [2; 3; 5; 7; 11; 13; 17]
list同样是不可变的(immutable):操作符“::”并未真正改变原list本身,相反的,它创建了一个新的list。示例:
> let people = [ "Adam"; "Dominic"; "James" ];;
val people : string list
> people;;
val it : string list = [ "Adam"; "Dominic"; "James" ]
> "Chris" :: people;;
val it : string list = [ "Chris"; "Adam"; "Dominic"; "James" ]
> people;;
val it : string list = [ "Adam"; "Dominic"; "James" ]
如你所见,people并未被改变。在内存中,F#将list表示为关联的list;每个F#的list的值(value)包含了自身的值以及指向下一个列表的指针。也就是说当你使用“::”来创建一个新的list的时候,新list的尾部就包含了一个指向老list的指针。
在我看来,通过不可变性与指针的结合,提高了list的内存利用效率。
我们再看一个分解(decompose)list的例子:
let oddPrimes = [3; 5; 7; 11]
let printFirst primes =
match primes with
| h :: t -> printfn "The first prime in the list is %d" h
| [] -> printfn "No primes found in the list"
> printFirst oddPrimes;;
The first prime in the list is 3
val it : unit = ()