为什么是toList(1,2)== [2] [英] Why is toList (1, 2) == [2]

查看:136
本文介绍了为什么是toList(1,2)== [2]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如问题所述,为什么 toList(1,2)== [2]



我记得在元组上映射时发生了类似的情况,但我不记得为什么或者它是相关的。

(1,2)不会相应列表 [1,2] 。这是没有道理的:那么(True,3.14)会相应于什么?您不能拥有列表 [True,3.14] ,因为列表只能包含单个类型的元素。 (Haskell与Python的不同之处在于这里。)



从任何元组中挑选保证单一类型的元素的唯一方法是,只需要一个单个元素。因此,从 Foldable(a,)实例生成的元素 toList 取元组(a ,b)并产生列表 [b] 。很明显,在这样一个元组中总有一个 b 元素。

原则上可以考虑(Int,Int)作为元素具有相同类型的特殊情况,因此您可以选择两个而不是一个,但是这样的特殊处理需要一些非常尴尬的类型相等性检查。一般情况下,特殊情况下处理不是一个好主意。



可以说,最好不要定义 Foldable(a,) 实例,以避免这种混淆的行为。然后再次,有时使用 fold 来摆脱第一个元组元素(例如某个索引)是很方便的。



<为什么使用 b 而不是 a ?那种随意?那么,不完全。 (a,b)实际上是(,)ab 的语法糖,因此您可以考虑(,)a 作为函数(其元素的类型为 b ),但不能有函子 (`(,)`b),其元素将具有类型 a


As the question says, why is toList (1, 2) == [2]?

I remember something similar happening when fmapping on tuples, but I do not remember why or if it is related.

解决方案

(1,2) does not correspend to the list [1,2]. That wouldn't make sense: what would then (True, 3.14) correspend to? You can't have the list [True, 3.14], because a list can only contain elements of a single type. (Haskell is different from e.g. Python here.)

The only way to pick elements of guaranteed a single type from any tuple is, well, to take only a single element. Hence toList, as generated from the Foldable (a,) instance, takes tuples (a,b) and yields lists [b]. Obviously there's always exactly one b element in such a tuple.
You could in principle consider (Int, Int) as a special case where the elements have the same type and hence you can pick two instead of one, but such a special handling would require some highly awkward type-equality checking. And generally, special-case handling is not a good idea.

Arguably, it would have been better not to define the Foldable (a,) instance at all, to avoid this confusing behaviour. Then again, sometimes it's handy to use fold to just get rid of the first tuple element (e.g. some index).


Why use b and not a? Kind of arbitrary? Well, not completely. (a,b) is actually syntactic sugar for (,) a b, hence you can consider (,) a as a functor (whose elements have type b), but you can't have a functor (`(,)`b) whose elements would have type a.

这篇关于为什么是toList(1,2)== [2]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆