gpt4 book ai didi

haskell - 复杂状态 Monad 结构

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

我仍然是 Haskell 的新手,我想我现在已经无法理解了。我的代码如下所示。

data World = World {
intStack :: [Int],
boolStack :: [Bool]
} deriving Show

instance IntStack World where
getIntStack = intStack
putIntStack ints (World _ bools) = World ints bools

instance BoolStack World where
getBoolStack = boolStack
putBoolStack bools (World ints _) = World ints bools

class IntStack a where
getIntStack :: a -> [Int]
putIntStack :: [Int] -> a -> a

class BoolStack a where
getBoolStack :: a -> [Bool]
putBoolStack :: [Bool] -> a -> a

(<=>) :: (IntStack c, BoolStack c) => c -> c
(<=>) w = putIntStack xs . putBoolStack ((x == x'):bs) $ w
where (x:x':xs) = getIntStack w
bs = getBoolStack w

(<+>) :: (IntStack c) => c -> c
(<+>) w = putIntStack ((x+x'):xs) w
where (x:x':xs) = getIntStack w

我的重点(目前忽略函数中的错误情况)是能够将 (<=>) 和 (<+>) 等函数链接在一起,假设底层数据类型实现了函数所需的接口(interface)。

我觉得我可以用状态单子(monad)来清理它,但我不确定如何构造它以允许更改实现 IntStack、BoolStack 等的任何数据类型。

我知道这是一个非常模糊的描述,但我觉得我上面的代码可能是绝对错误的方法。

感谢您的反馈!

最佳答案

class IntStack a where
getIntStack :: a -> [Int]
putIntStack :: [Int] -> a -> a

class BoolStack a where
getBoolStack :: a -> [Bool]
putBoolStack :: [Bool] -> a -> a

恭喜,您刚刚发明了镜头!摘要[Int][Bool]类型,并使用 data而不是class ,你会得到类似的东西

data Lens a b = Lens
{ get :: a -> b
, put :: b -> a -> a
}

...它在 Hackage 上的六个包中实现。大多数至少提供:

  • 能够导出像您的 getIntStack 这样的投影镜头/putIntStackgetBoolStack/putBoolStack直接来自数据声明
  • 水平构图(运行第一个镜头,然后运行第二个镜头 - 例如,首先从一些较大的结构中选取 World,然后从 intStack 中选取 World )和垂直构图(运行两个镜头)平行,每个在一对的一侧)
  • State的一些接口(interface)和StateT (例如 Lens a b -> State b r -> State a r 类型的东西),这将允许您在 [Bool] 上编写计算或[Int]并像在 World 上进行计算一样运行它们

所以,看看黑客攻击!有data-lens家庭,其中包括 a core , the deriving ability ,和the stateful interface ; lens包裹;和 pointless-lenses包裹。可能还有一些我忘记了。

关于haskell - 复杂状态 Monad 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7710211/

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