Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/10.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 在'newtype'参数中指定元组_Haskell_Newtype - Fatal编程技术网

Haskell 在'newtype'参数中指定元组

Haskell 在'newtype'参数中指定元组,haskell,newtype,Haskell,Newtype,讨论newtype 它的对b a的签名如何表示传入的参数必须是元组 ghci> newtype Pair b a = Pair { getPair :: (a, b) } ghci> let p = Pair (5, 10) 我很困惑ba如何表示元组。传入元组的原因不是类型,而是它的构造函数: Pair { getPair :: (a, b) } 这用于使用一个名为getPair的字段定义一个Pair构造函数,该字段包含一个元组。通过将其分为两部分,可以获得非常相似的效果: ne

讨论
newtype

它的
对b a的签名如何表示传入的参数必须是元组

ghci> newtype Pair b a = Pair { getPair :: (a, b) }
ghci> let p = Pair (5, 10)

我很困惑
ba
如何表示元组。

传入元组的原因不是类型,而是它的构造函数:

Pair { getPair :: (a, b) }
这用于使用一个名为
getPair
的字段定义一个
Pair
构造函数,该字段包含一个元组。通过将其分为两部分,可以获得非常相似的效果:

newtype Pair b a = Pair (a, b)

getPair (Pair (x, y)) = (x, y)

因此
ba
不会强制它成为元组;这就是
{getPair::(a,b)}
所做的。

之所以会产生混淆,是因为您的数据类型名称和构造函数名称都指定为
Pair
。相反,您可以等效地编写

newtype Pair b a = MkPair { getPair :: (a, b) }
然后你就可以用

> let p = MkPair ("test", 10) :: Pair Int String


构造函数和类型名不共享名称空间,因此它们可以具有相同的名称而不会发生冲突。此模式通常用于新类型,因为类型名通常也是构造函数的良好描述性名称。这也适用于使用
data
关键字声明的类型。

s/名为getTuple的单个字段/名为getPair的单个字段/