SML:运算符 ```::``` 是正确结合的并且应该用作 ```<value of type a>::<list with elements of type a>``` 是真的吗?
SML: Operator ```::``` is it true that is right assosiative and shoud be used as ```<value of type a>::<list with elements of type a>```?
好吧,我对 cons 运算符有点困惑:::
我知道这是可以接受的:
> [2]
or this
2::[2,4]
> [2,2,4]
and i know this is forbbiden
[2]::[3]
it won't work.
but I recently found out that :
[2]::[3]::nil
will work :
> [[2],[3]]
or
[2]::[] will do as well.
>[[2]]
我的问题是为什么?
我在想,也许这是一条规则,比如如果我有一个类型为 a 的列表,那么我只能创建一个类型为 a 的新列表。
例如,当我有
[2] :: [3]
My lists have elements of type int but I am asking to concatenate into an int list a non init value [3] ??
But when I have [2]::[3]::[] , the empty list [] could be an empty list of any type so here I need it to be an empty list, with elements like [3], so it adds to the nil the element [3] and then the element [2] and so on ...
So is that the reason? Is there something else?
在SML中,列表定义如下:
datatype 'a list = nil | :: of 'a * 'a list
特别地,::
是类型 'a * 'a list -> 'a list
的中缀构造函数。
语法 [1, 2, 3]
是 1 :: 2 :: 3 :: nil
的糖分。
您不仅需要构造包含 int
的列表(即,其中 'a = int
);例如,你可以有列表 containing int list
s,即 int list list
。那是你创造的:
[2] :: [3] :: nil
(* can be sugared as *)
[[2], [3]]
(同样,您可以选择 'a = string
并创建列表 "hello" :: "world" :: nil
,即 ["hello", "world"]
。)
如果要追加两个列表,可以使用中缀 @
,其类型为 'a list * 'a list -> 'a list
。例如:
[1, 2] @ [3]
(* evaluates to [1, 2, 3] *)
好吧,我对 cons 运算符有点困惑:::
我知道这是可以接受的:
> [2]
or this
2::[2,4]
> [2,2,4]
and i know this is forbbiden
[2]::[3]
it won't work.
but I recently found out that :
[2]::[3]::nil
will work :
> [[2],[3]]
or
[2]::[] will do as well.
>[[2]]
我的问题是为什么? 我在想,也许这是一条规则,比如如果我有一个类型为 a 的列表,那么我只能创建一个类型为 a 的新列表。 例如,当我有
[2] :: [3]
My lists have elements of type int but I am asking to concatenate into an int list a non init value [3] ??
But when I have [2]::[3]::[] , the empty list [] could be an empty list of any type so here I need it to be an empty list, with elements like [3], so it adds to the nil the element [3] and then the element [2] and so on ...
So is that the reason? Is there something else?
在SML中,列表定义如下:
datatype 'a list = nil | :: of 'a * 'a list
特别地,::
是类型 'a * 'a list -> 'a list
的中缀构造函数。
语法 [1, 2, 3]
是 1 :: 2 :: 3 :: nil
的糖分。
您不仅需要构造包含 int
的列表(即,其中 'a = int
);例如,你可以有列表 containing int list
s,即 int list list
。那是你创造的:
[2] :: [3] :: nil
(* can be sugared as *)
[[2], [3]]
(同样,您可以选择 'a = string
并创建列表 "hello" :: "world" :: nil
,即 ["hello", "world"]
。)
如果要追加两个列表,可以使用中缀 @
,其类型为 'a list * 'a list -> 'a list
。例如:
[1, 2] @ [3]
(* evaluates to [1, 2, 3] *)