Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Haskell 如何创建包含列表的数据类型_Haskell - Fatal编程技术网

Haskell 如何创建包含列表的数据类型

Haskell 如何创建包含列表的数据类型,haskell,Haskell,我正在尝试创建包含以下列表的数据类型类: data Test = [Int] deriving(Show) 但是Haskell不能解析构造函数。我在这里做错了什么?我如何才能最好地实现我想做的事情?答案 您需要包含一个构造函数,但还没有这样做 data Test = Test [Int] 考虑查看Haskell的几个类型声明、它们的用法和语法 Haskell类型声明 数据 data Options = OptionA Int | OptionB Integer | OptionC Puppy

我正在尝试创建包含以下列表的数据类型类:

data Test = [Int] deriving(Show)
但是Haskell不能解析构造函数。我在这里做错了什么?我如何才能最好地实现我想做的事情?

答案 您需要包含一个构造函数,但还没有这样做

data Test = Test [Int]
考虑查看Haskell的几个类型声明、它们的用法和语法

Haskell类型声明 数据

data Options = OptionA Int | OptionB Integer | OptionC PuppyAges
      ^           ^     ^      ^        ^        ^         ^
      |           |   Field    |        |        |         |
    type         Constructor   |        |     Constructor  |
                         Constructor   Field              Field
    deriving (Show)

myPuppies = OptionB 1234
允许声明零个或多个构造函数s,每个构造函数具有零个或多个字段

newtype

newtype PuppyAges = AgeList [Int] deriving (Show)

myPuppies :: PuppyAges
myPuppies = AgeList [1,2,3,4]
type IntList = [Int]

thisIsThat :: IntList -> [Int]
thisIsThat x = x
允许用一个字段声明一个构造函数。这个领域很严格

类型

newtype PuppyAges = AgeList [Int] deriving (Show)

myPuppies :: PuppyAges
myPuppies = AgeList [1,2,3,4]
type IntList = [Int]

thisIsThat :: IntList -> [Int]
thisIsThat x = x
允许创建一个类型别名,该别名可以在任何情况下与equals右边的类型进行文本交换

构造函数

允许创建声明类型的值。还允许分解值以获得单个字段(通过模式匹配)

例子 数据

data Options = OptionA Int | OptionB Integer | OptionC PuppyAges
      ^           ^     ^      ^        ^        ^         ^
      |           |   Field    |        |        |         |
    type         Constructor   |        |     Constructor  |
                         Constructor   Field              Field
    deriving (Show)

myPuppies = OptionB 1234
newtype

newtype PuppyAges = AgeList [Int] deriving (Show)

myPuppies :: PuppyAges
myPuppies = AgeList [1,2,3,4]
type IntList = [Int]

thisIsThat :: IntList -> [Int]
thisIsThat x = x
因为类型(puppeyages)和构造函数(AgeList)在不同的名称空间中,所以人们可以并且经常使用相同的名称,例如
newtype X=X[Int]

类型

newtype PuppyAges = AgeList [Int] deriving (Show)

myPuppies :: PuppyAges
myPuppies = AgeList [1,2,3,4]
type IntList = [Int]

thisIsThat :: IntList -> [Int]
thisIsThat x = x
构造函数s(更多)


缺少数据构造函数名称。如果你的类型只是一个列表的包装,那么你可能还需要一个数据构造函数名在
[Int]
前面。当然@WillNess,抱歉,如果不清楚的话,我在读《为你学哈斯克尔》(Haskell)一书。第7章中的示例不包括列表,有些示例没有构造函数名称。在询问之前,我可能应该对它做更多的修改,但不管怎样,我现在已经在使用newtype了。