学习类型的签名

发布于 2025-02-13 02:30:21 字数 1551 浏览 0 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

第几種人 2025-02-20 02:30:21

如果我得到一个说“输入以下表达式的类型签名”的任务,我被卡住了

,这也是一个愚蠢的任务。由于某种原因,Haskell课程一直以这种方式询问,但这很愚蠢。推断类型是编译器(特别是其Typechecker)的任务,或者是学习类型理论的另一种方法,而不是学习Haskell的人。

不要误会我的意思,这肯定是您最终可以轻松做的事情,但这不是您应该如何考虑Haskell代码。它几乎总是相反:您有一些上下文,您会看到一个差距知道它应该是什么,然后您找到与类型匹配的表达式表达式的类型。 (尽管有时您确实需要首先找出一个表达式的类型,以了解您需要写的表达式应该具有哪种类型。)

但是,您绝对需要学习的是理解类型签名。通过手练习类型的推断是到达那里的一种方法,但更有效的方法是两者都读了很多haskell代码。该代码的作用并不重要,只需选择您发现有趣的项目并查看其HADDOCK文档(通常最容易在 hackage )。选择任何功能,并尝试了解为什么给定描述对应于指定类型。然后查看源并通过实现跟踪类型。

另外,只要与GHCI一起玩很多玩具,想想您想解决的简单问题。也许像Project Euler这样的竞赛,但我从来没有亲自参加过。

If I get a task that says "enter the type signatures of the following expressions", I am stuck

Well, and that's a silly task too. For some reason Haskell courses keep asking it this way, but it's stupid. Inferring types is a task for a compiler (specifically its typechecker), or to put it another way for somebody learning type theory, but not for somebody learning Haskell.

Don't get me wrong, this is certainly something you will eventually be able to do easily, but it's not how you should in practice think about Haskell code. It almost always goes the other way around: you have some context, you see a gap an know what it's type is supposed to be, and then you find an expression that matches the type, not try to find the type of an expression. (Although, sometimes you do need to first find out the type of one expression in order to know what type the expression you need to write should have.)

However, what you absolutely need to learn is understanding type signatures. Practicing type inference by hand is one way of getting there, but more effective is to just both read an write lots of Haskell code. Doesn't really matter what the code does, just pick any project you find interesting and look at its Haddock documentation (usually easiest on Hackage). Pick any function, and try to understand why the given description corresponds to the specified type. Then look at the source and trace the types through the implementation.

Also, just toy around a lot with GHCi, think of simple problems you'd like to solve. Perhaps contests like Project Euler, but I never did that personally.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文