【发布时间】:2016-04-06 19:38:17
【问题描述】:
我正在使用“Haskell Programming from First Principles”这本书来学习 Haskell,在第 4 章“基本数据类型”快结束时,我遇到了一些让我感到困惑的事情。这本书提到了一个函数length,并说它适用于Listss。一切都很好,但是当我用各种Tuples 尝试这个length 函数时,我所看到的让我感到困惑:
首先我们看看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 的类型吗?还是在幕后发生了其他事情?
【问题讨论】:
-
是的,这是一个常见的抱怨 - 这是因为
Foldable仅与元组的最后一部分一起使用的方式以及Foldable的实例 2-tuples 仅适用于那些- 我建议你按原样处理 - 如果你愿意,你可以找到很多关于这个的讨论 - 这里是 example: Haskell Foldable Wats -
更混乱awaits me here!我还没有看到这个。
-
还有some empathy for my poor mind。但是,混乱仍然存在:(
标签: haskell