Haskell pro

From findscripter/everything-skills · View interactive version

Haskell pro is an AI agent skill from the GitHub repository findscripter/everything-skills. 当用 Haskell 构建强类型纯函数式服务/库/系统,或攻克高级类型系统、纯度边界、并发与性能优化时使用;做类型驱动建模、STM/async 并发、解析与属性测试齐备的可编译 Haskell 代码;不适用于一次性脚本、只问基础语法、无法引入 Haskell 或纯运行时性能调优场景;触发词:Haskell、GADT、typeclass、STM、Monad、Aeson、QuickCheck、Cabal。

How to use this skill

Skill file

何时使用

不该用的边界:

步骤 / 指令

1. 明确约束:纯度边界(IO 隔离到哪一层)、性能目标、并发模型(STM/async/轻量线程)、目标平台与 GHC 版本。
2. 类型驱动建模:用 newtype + 不变量、phantom type、必要时 GADT/type family 把领域规则编译期化;
   优先 total function,给出 Maybe/Either 而非 head/fromJust 这类 partial function。
3. 隔离副作用:纯逻辑与 effectful 代码分层;IO 收束到显式边界,业务核心保持可纯测。
4. 抽象克制:只在能提升清晰度时引入 typeclass / 代数设计,并尊重其 law;语言扩展按需开、逐条说明用途。
5. 实现 + 测试同步:Hspec 写示例测试,QuickCheck 写属性测试驱动不变量;示例尽量 GHCi 可跑或可直接编译。
6. 并发用 STM 做可组合事务,async 管理并发任务,配 exception-safe 组合子(bracket/finally)防资源泄漏。
7. 仅在热点处优化:先 profiling(-prof / +RTS -p)定位,再上 strictness(BangPatterns/seq)、避免 thunk 堆积、利用 fusion;不要凭感觉提前优化。
8. 过质量门:cabal build / stack build、hlint、测试全绿;模块保持小而显式、依赖卫生(pin 版本)。

核心规则:

示例

最小工程骨架与质量门命令:

cabal init --non-interactive -p mysvc   # 或 stack new mysvc
cabal build
cabal repl                              # GHCi 交互
cabal test
hlint src/                              # 风格与反模式 lint
cabal build --enable-profiling && cabal run -- +RTS -p   # 热点剖析

用类型把不变量编译期化(newtype + phantom type):

{-# LANGUAGE GeneralizedNewtypeDeriving #-}
newtype UserId = UserId Int deriving (Eq, Ord, Show)
newtype Email  = Email Text  deriving (Eq, Show)
-- 构造器不导出,只暴露经校验的 smart constructor,保证「类型存在即合法」
mkEmail :: Text -> Either Text Email
mkEmail t | "@" `T.isInfixOf` t = Right (Email t)
          | otherwise           = Left "invalid email"

total function 取代 partial function:

-- 不要:head xs(空列表会 panic)
safeHead :: [a] -> Maybe a
safeHead []      = Nothing
safeHead (x:_)   = Just x

STM 可组合事务 + async 并发:

import Control.Concurrent.STM
import Control.Concurrent.Async (mapConcurrently)

transfer :: TVar Int -> TVar Int -> Int -> STM ()
transfer from to n = do
  modifyTVar' from (subtract n)
  modifyTVar' to   (+ n)
-- atomically (transfer a b 100)  -- 整个事务原子提交
-- mapConcurrently fetchUrl urls  -- 并发抓取并聚合结果

Aeson 解析 / QuickCheck 属性测试:

import Data.Aeson (FromJSON, decode)
import Test.QuickCheck

prop_reverseTwice :: [Int] -> Bool
prop_reverseTwice xs = reverse (reverse xs) == xs
-- quickCheck prop_reverseTwice

典型请求样例(可直接当提示词):

注意事项

互见


采编自 sickn33/antigravity-awesome-skills(源技能 haskell-pro,MIT 许可)。

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.