类型检查过的非空字符串
Type-checked non-empty strings

原始链接: https://exploring-better-ways.bellroy.com/haskell-koan-type-checked-non-empty-strings.html

Bellroy 的工程师通过将数千个 TemplateHaskell (TH) 调用替换为经过编译时验证的 `NonEmptyText` 构造函数,使一个数据密集型包的构建时间缩短了约 10%。 团队利用 GHC 9.10 的 `RequiredTypeArguments` 特性,将类型层级的字符串字面量直接传递给函数。通过定义一个利用 `Unsatisfiable` 的自定义类型类(`IsNonEmptySymbol`),当输入空字符串时,系统能触发针对性的错误消息,从而确保无效状态在编译时即无法表示。 这种方法避免了在编译期间求值的 TH 拼接开销。作者将此模式扩展到了更复杂的验证场景(例如 DynamoDB 表名解析),通过使用类型层级的循环(type-family loops)在类型层面执行算法检查。尽管 Haskell 中的类型层级编程存在限制(如严格的归约限制和复杂的语法),但这一技术迈向了更稳健、类似于依赖类型设计的重要一步,证明了经过类型检查的常量既能保持高性能,又具备良好的表达能力。

```Hacker News 最新 | 过往 | 评论 | 提问 | 展示 | 招聘 | 提交 登录 类型检查的非空字符串 (bellroy.com) 8 分,由 surprisetalk 发布于 1 小时前 | 隐藏 | 过往 | 收藏 | 讨论 | 帮助 指南 | 常见问题 | 列表 | API | 安全 | 法律 | 加入 YC | 联系 搜索: ```
相关文章

原文

This post is a Haskell koan. We’ll get to the background and motivation, but the goal here is to share a small and uncommon technique that we’ve employed, and enjoyed; perfect blog fodder.

In short, we wrote a type-checked non-empty string constructor, replaced thousands of equivalent TemplateHaskell calls, for a ~10% build-time improvement in a large and data-heavy package that made many calls to it.

introduced in GHC 9.10, lets us pass a type-level string literal into a function as if it were a value. We can throw a custom type error message like "Expected a non-empty string" if we (at the type-level) see an empty string; like so:

Dependent Haskell which is slowly-but-surely inching closer to reality with every major GHC release. Languages like Idris and Lean have it today, but for better or worse, Haskell is the language in this space with the most adoption and inertia. GHC developers: please continue! 🙂

联系我们 contact @ memedata.com