gpt4 book ai didi

haskell - 为什么长度为具有 2 个元素的元组返回 1,并为具有更多元素的元组给出错误?

转载 作者:行者123 更新时间:2023-12-03 10:25:44 24 4
gpt4 key购买 nike

我正在使用“Haskell Programming from First Principles”一书学习 Haskell,在第 4 章“基本数据类型”的末尾,我遇到了一些让我感到困惑的事情。书中提到了一个函数length并说它适用于 Lists s。一切都很好,但是当我尝试这个 length各种功能Tuple s,我看到的让我很困惑:

首先我们看一下length的类型:

:t length
length :: Foldable t => t a -> Int

好的,所以我在上面读到“采用一个可折叠的,我认为它是一个方便的列表,并返回一个 Int,即列表中元素的数量。”因此,我的第一个困惑是:为什么以下内容会起作用:
length (1, 1)
1

因为对我来说,似乎我刚刚将一个包含两个元素的元组传递给 length ,它返回 1。元组是一个列表吗?元组是可折叠的吗?当然,为什么 1 ?

现在我更进一步:
length (1, 1, 1)

<interactive>:6:1:
No instance for (Foldable ((,,) t0 t1))
arising from a use of ‘length’
In the expression: length (1, 1, 1)
In an equation for ‘it’: it = length (1, 1, 1)

<interactive>:6:9:
No instance for (Num t0) arising from the literal ‘1’
The type variable ‘t0’ is ambiguous
Note: there are several potential instances:
instance Num Integer -- Defined in ‘GHC.Num’
instance Num Double -- Defined in ‘GHC.Float’
instance Num Float -- Defined in ‘GHC.Float’
...plus two others
In the expression: 1
In the first argument of ‘length’, namely ‘(1, 1, 1)’
In the expression: length (1, 1, 1)

<interactive>:6:12:
No instance for (Num t1) arising from the literal ‘1’
The type variable ‘t1’ is ambiguous
Note: there are several potential instances:
instance Num Integer -- Defined in ‘GHC.Num’
instance Num Double -- Defined in ‘GHC.Float’
instance Num Float -- Defined in ‘GHC.Float’
...plus two others
In the expression: 1
In the first argument of ‘length’, namely ‘(1, 1, 1)’
In the expression: length (1, 1, 1)

另一个尝试:
length (1::Int, 1::Int, 1::Int)

<interactive>:7:1:
No instance for (Foldable ((,,) Int Int))
arising from a use of ‘length’
In the expression: length (1 :: Int, 1 :: Int, 1 :: Int)
In an equation for ‘it’: it = length (1 :: Int, 1 :: Int, 1 :: Int)

但以下工作:
length (1::Int, 1::Int)
1

我在上面观察到的行为有什么好的解释吗?我是否误读了 length 的类型? ?还是在幕后发生了其他事情?

最佳答案

你遇到了一个引发了很多讨论和咬牙切齿的 Haskell 事业。

基本上,就 Foldable 而言(提供 length 的类型类),2 元组不被认为是两个元素的容器,而是一个元素的容器,伴随着一些上下文。

您可以提取 a 类型的元素列表来自任何 Foldable a .请注意,对于 2 元组,Foldable 的类型变量是元组的第二个元素的类型,它可以与第一个元素的类型不同。

如果您有 ('c',2) :: (Char,Int)元组,你不能提取两个 Int 并不神秘在那种情况下!但是当类型相等时,它会变得困惑。

至于为什么length (1::Int, 1::Int, 1::Int)失败,三元组没有 Foldable实例定义,但也许他们应该有一个,以保持一致性。 3 元组的长度也为 1。

顺便说一句,Identity可以认为是一种 1 元组的仿函数也是 Foldable当然也有长度 1。

如果 Foldable元组的实例是否存在?我认为支持"is"的基本哲学是,我们称之为“充分”之一。如果一个类型可以以一种定义明确、合法的方式成为一个类型类的实例,那么它应该有那个实例。即使它看起来不是很有用,并且在某些情况下可能会令人困惑。

关于haskell - 为什么长度为具有 2 个元素的元组返回 1,并为具有更多元素的元组给出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36460833/

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