包含不同类型的列表 [英] List containing different types

查看:67
本文介绍了包含不同类型的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在编写自己的结构,该结构可以同时处理整数和字符串:

I am currently writing my own structurewhich can handle ints and strings at the same time:

类似

data Collection = One Int | Two String | Three(Collection)(Collection)

但是,我试图编写一个可以将结构转换为列表的函数.

However, I was trying to write a function which could convert my structure into a list.

我正确地认为这是不可能的,因为默认情况下会这样做:

Am I right in thinking this is impossible because, by default doing:

[1,2,测试"]

[1,2,"test"]

在控制台中不起作用,因此我的功能注定总是会失败吗?

in the console doesn't work and therefore my function is bound to always fail?

推荐答案

您可能应该定义

type Collection = [Either Int String]

然后,而不是这样做

l = [1,2,"test"]

你可以做

l :: Collection
l = [Left 1, Left 2, Right "test"]

如果要使用两种以上类型,则需要定义自己的成员类型.所以你也会做类似的事情

If you want more than two types, you'll need to define your own member type. So you would do something like this aswell

data MemberType = MyInt Int | MyString String | MyFloat Float deriving Show
type Collection = [MemberType]
l :: Collection
l = [MyInt 1, MyInt 2, MyString "test", MyFloat 2.2]

deriving Show不是必需的,但是很高兴能够简单地执行print l来以一种很好的方式打印列表.

The deriving Show isn't necessary, but it's nice to be able to simply do print l to print the list in a nice way.

这篇关于包含不同类型的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆