gpt4 book ai didi

haskell - Haskell 中具有多个参数的新类型

转载 作者:行者123 更新时间:2023-12-02 01:26:46 25 4
gpt4 key购买 nike

在 Haskell 中,我尝试调用我已声明的以下两个 newtypes

为什么这有效:

newtype CharList = CharList { get2CharList :: [Char] } deriving (Eq, Show)   

ghci> CharList "some"
CharList {get2CharList = "some"}

当这不起作用时:

newtype Pair a b = Pair { createPair :: (a, b) } deriving (Eq, Show)

ghci> Pair 2 4
<interactive>:13:1: error:
* Couldn't match expected type: t0 -> t
with actual type: Pair a0 b0
* The function `Pair' is applied to two value arguments,
but its type `(a0, b0) -> Pair a0 b0' has only one
In the expression: Pair 2 4
In an equation for `it': it = Pair 2 4
* Relevant bindings include it :: t (bound at <interactive>:13:1)

是否需要 Monad 才能工作,如下所示:The Writer monad and its type declaration在调用 newtype 时我是否必须限制类型?

此外,如果我想要一个 newtype 接受更多参数(例如 3),我该怎么做?

最佳答案

Pair newtype 被声明为包含(或包装)值的元组,因此您必须提供它来创建值:

ghci> Pair (2, 4)
Pair {createPair = (2,4)}

您可以使用 createPairPair 值中提取元组:

ghci> createPair $ Pair (2, 4)
(2,4)

虽然类型Pair a b(不带括号或逗号)的形式给出,但数据构造函数需要一个元组。类型声明在等号左边,数据构造函数在等号右边。

语法 Pair (2, 4) 只是完整数据构造函数的简写,这也是可能的:

ghci> Pair { createPair = (2, 4) }
Pair {createPair = (2,4)}

您可以用相同的方式创建具有更多类型参数的包装器:

newtype Triple a b c = T { getTriple :: (a, b, c) } deriving (Eq, Show)

此示例还展示了一些可能有助于理解上述内容的内容。类型的名称不必与数据构造函数的名称相同。这里,类型的名称是 Triple,而数据构造函数的名称是 T

使用数据构造函数 T 创建一个值 Triple:

ghci> T (1, "foo", True)
T {getTriple = (1,"foo",True)}

该表达式的类型是:

ghci> :t T (1, "foo", True)
T (1, "foo", True) :: Num a => Triple a String Bool

关于haskell - Haskell 中具有多个参数的新类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74419263/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com