隔壁讨论 string.join()

2019-11-16 08:59:01 +08:00
 crella
转帖
http://m.newsmth.net/article/Programming/174359?p=1
3254 次点击
所在节点    Python
6 条回复
sagaxu
2019-11-16 09:58:42 +08:00
真是矫情,看看隔壁 PHP,光名字就有俩,implode 和 join,参数顺序还任意,四种等价组合任君搭配。
taotaodaddy
2019-11-16 10:27:44 +08:00
好无聊的讨论
inhzus
2019-11-16 10:35:31 +08:00
好消息好消息,本 xx 已经和 Google 达成战略合作,大家有问题都可以去查 Google 啦。
(哪怕去查下 Google 也不会有这样的疑问,把 stack overflow 的回答贴过来: https://stackoverflow.com/questions/493819/why-is-it-string-joinlist-instead-of-list-joinstring
Guido 当时讨论的 thread,往后翻几页就能看到了: https://mail.python.org/pipermail/python-dev/1999-June/095366.html

There were four options proposed in this thread:
str.join(seq)
seq.join(str)
seq.reduce(str)
join as a built-in function

1. Guido wanted to support not only lists, tuples, but all sequences/iterables.
2. seq.reduce(str) is difficult for new-comers.
3. seq.join(str) introduces unexpected dependency from sequences to str/unicode.
4. join() as a built-in function would support only specific data types. So using a built in namespace is not good. If join() supports many datatypes, creating optimized implementation would be difficult, if implemented using the __add__ method then it's O(n²).
5. The separator string (sep) should not be omitted. Explicit is better than implicit.
ClericPy
2019-11-16 17:42:21 +08:00
3 楼厉害 ...

以前只感觉给 str 加个接口比给所有奇怪迭代器加接口要安全省事, 没想到这么多条件
secondwtq
2019-11-16 22:57:58 +08:00
简单过了一下,挺民科的 ... 或者说挺 GvR 的吧
没啥营养,排版也不舒服就没仔细看

我来做的话会做成 join :: Show a => String -> List a -> String
纯从签名角度,join 是容器和 String 共有的行为,做进哪个里面都不合适
但是由于是两个参数,这就又有参数顺序问题,参数顺序问题和是 string.join(list) 还是 list.join(string) 本质上是一个问题
把 String 放在前面的原因是这样对 partial application 更友好(和 fmap 的参数顺序是一个道理),很方便能定义 joinBySpace = join " " 和 joinByComma = join ", " 之类的。
当然并不是说函数签名*就应该*以”对 partial application 友好“为原则而设计,我记得看到过相关的观点说这样很不自然什么的,但是如果编程环境中所有的函数都统一以”对 partial application 友好“为基本原则,那么至少参数顺序是*可预测的*,这种一致,没有 surprise 的特征比所谓的”合理“更重要
就好像显示输入设备的颜色问题,虽然很多终端设备的色域和色准很垃圾,但是即使不做印刷品,设计师也一定要在标准化且精确的颜色配置下工作,因为如果设计师统一了那起码还是有标准的,如果设计师都不统一,最后的结果完全无法预测

当然 Python 不搞 partial application 之类的幺蛾子所以就没有这么做的理由,”join() as a built-in function would support only specific data types“ 也挺扯淡的 ...
secondwtq
2019-11-16 23:18:22 +08:00
@secondwtq 不过”对 partial application 友好“和 Python 的”support not only lists, tuples, but all sequences/iterables“其实有点点相通。

只要这一条就够了,因为主要目的是保证一致性。再多的规则用户是难以判断的。很多事情就是说起来漂亮,但是实际情况没这么简单,所以最后吵得什么”优美“应该看的是在各种复杂情况下有没有始终坚持十九项基本原则 ... 哦不是一套简单明确容易理解的规则

光 Zen of Python 就十九条了 ...

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/620098

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX