如何在 Haskell 中对类型类进行分组

day*_*ion 3 haskell

目的是使类型类约束代码更清晰。

type CanThrowDice = (Monad m, MonadIO m, Random a)

throwDice :: CanThrowDice m a => (a, a) -> m a
throwDice (r1, r2) = ...
Run Code Online (Sandbox Code Playgroud)

而不是写:

throwDice ::  (Monad m, MonadIO m, Random a) => (a, a) -> m a
throwDice (r1, r2) = ...
Run Code Online (Sandbox Code Playgroud)

我记得在某处看到过这种用法,但不记得了。上面的代码警告我添加一些额外的编译指示,例如ConstraintKinds我无法使其工作。

Wil*_*sem 6

这是唯一缺少的是类型参数maConstraintKinds语言编译[GHC-DOC]

{-# LANGUAGE ConstraintKinds #-}

--                ↓ ↓ type parameters
type CanThrowDice m a = (Monad m, MonadIO m, Random a)

throwDice :: CanThrowDice m a => (a, a) -> m a
throwDice (r1, r2) = …
Run Code Online (Sandbox Code Playgroud)