简体   繁体   English

列表与F#中的[]之间的差异

[英]Difference between list and [] in F#

I am porting some Haskell code to F# but a bit confused about the collections available and their signatures in F#. 我正在将一些Haskell代码移植到F#,但对F#中可用的集合及其签名有点困惑。 My understanding is that elements in lists are enclosed between [ ], sequences between { }, and arrays between [| 我的理解是列表中的元素包含在[]之间,{}之间的序列和[|之间的数组]之间 |]. |]。 In F# Interactive, I get the following when I create each container with 5 ints. 在F#Interactive中,当我用5个int创建每个容器时,我得到以下内容。

// List
> [1..5]
val it : int list = [1; 2; 3; 4; 5]

// Seq
> {1..5}
val it : seq<int> = seq [1; 2; 3; 4; ...]

// Array
> [|1..5|]
val it : int [] = [|1; 2; 3; 4; 5|]

What confuses me is that the type signature for arrays is int [] . 令我困惑的是,数组的类型签名是int [] May be type int array or int [||] would be less confusing? 可能是类型int arrayint [||]会不那么混乱? Looking at the type signature, I tend to think it is a list, especially because an empty list is also represented as []. 查看类型签名,我倾向于认为它是一个列表,特别是因为空列表也表示为[]。

One question here: why is sequence type seq<int> and not int seq . 这里有一个问题:为什么序列类型为seq<int>而不是int seq I am assuming this may be syntactic sugar but may be there is something else behind this. 我假设这可能是语法糖,但可能还有其他背后的东西。

Now creating new types using the collection: 现在使用集合创建新类型:

type T1 = T1 of int list
type T2 = T2 of int seq // becomes type T2 = T2 of seq<int>
type T3 = T3 of int array
type T4 = T4 of int []

Is T3 and T4 the same thing? T3和T4是一回事吗?

F# allows you to use .Net style type definitions and ocaml style type definitions. F#允许您使用.Net样式类型定义和ocaml样式类型定义。 These are the same. 这些都是一样的。

int list
list<int>  

int seq
seq<int>

int array
array<int>

Some Expressions in F# are F#中的一些表达式

[||] is an array
[] is a list
{} is a sequence

In a type definition you can also do int [] . 在类型定义中,您也可以执行int [] Which is C like syntax sugar. 哪个是C语法糖。 Yep, T3 and T4 are the same. 是的,T3和T4是一样的。

You can't however do this []<int> . 但是你不能这样做[]<int> [] is a bit strange since it behaves as the type array in a type definition and as op_Nil in an expression. []有点奇怪,因为它在类型定义中表现为类型数组,在表达式中表现为op_Nil。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM