gpt4 book ai didi

haskell - 为什么状态单子(monad)通常使用 newtype 而不是 type

转载 作者:行者123 更新时间:2023-12-03 02:19:58 24 4
gpt4 key购买 nike

我见过的几乎所有 State Monad 示例都被包装在 newtype 中。

{-# LANGUAGE GeneralizedNewtypeDeriving #-}

import Control.Monad.State
import Control.Applicative

data Bazzar
= Bazzar {
valueOne :: Int
, valueTwo :: Int
}

newtype BazState a = BazState { unBazify :: State Bazzar a }
deriving (Functor, Applicative, Monad, MonadState Bazzar)

有什么理由让我不应该只创建类型别名吗?

type BazState a = State Bazzar a

我意识到 newtype 的目的是区分同一类型数据结构的两种不同用途,例如为现有类型重新实现类型类,或者如果您想区分类型的使用来自正常行为。或者实现其他类型类以使用该类

如果您没有执行上述任何操作,那么在这种情况下使用 newtype 是否只是不必要的间接?

最佳答案

除了能够定义新类型的实例之外,您还可以将其用作库的“封闭构造函数”API。这样,您就可以导出没有任何构造函数的单一类型,以及充当基元和组合器的函数,以便库的用户无法构造您类型的无效值。这也意味着,如果您足够小心,您可以更改底层结构,而不会破坏面向外部的 API。 Neil Mitchell 就是一个很好的例子,who said in a recent post about modifying the Shake build system to use the Continuation monad :

The cool thing about Haskell is that I've been able to completely replace the underlying Shake Action monad from StateT/IO, to ReaderT/IO, to ReaderT/ContT/IO, without ever breaking any users of Shake. Haskell allows me to produce effective and flexible abstractions.

关于haskell - 为什么状态单子(monad)通常使用 newtype 而不是 type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25462922/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com