2010-12-16 106 views
2

如何在ML中定义新数据类型,让我们假设newList,以便它可以包含元素'a(int,real等),嵌套列表的列表,例如: 如果我的类型'a是int,数值可能是:[1],[1,[4]],[1,[5],[[5]]]等 提前感谢任何帮助新列表数据类型

EDITED 对不起,没有1在这个例子中,我列出了不同的int列表,我把它删除了

回答

1

你不行。列表中的所有元素必须是相同的类型。在你的例子中,一些元素是int类型,有些是int list

您可以创建这样的树,但语法不是那么高兴:-)

datatype 'a multiList = Empty 
         | List of 'a multiList list 
         | E of 'a; 

val x = List [E 1, List [E 1, List [E 4]], List [E 1, List [E 5]]]; 
+0

你说得对,我改变了问题,你能帮忙吗? – rookie 2010-12-16 19:07:37

+0

@rookie,我已经更新了我的答案,因此它包含一个多态树:-)顺便说一句,我明天在Standard ML中进行检查。这是很好的锻炼一点:-) – 2010-12-16 19:39:37

+0

好运,谢谢你的答案! – rookie 2010-12-16 23:42:14

1
datatype 'a multiList = E of 'a 
         | List of 'a multiList list 

使用你的例子是:

List [E 1] 

List [E 1, List [E 4]] 

List [E 1, List [E 5], List [List [E 5]]]