Haskell 状态和类型类
我如何将 getX 和 putX 分组到类实例中? 下面的代码是这篇文章的答案 Haskell 中使用 State 的类设置方法-Monad
import Control.Monad.State
data Point = Point { x :: Int, y :: Int } deriving Show
getX :: State Point Int
getX = get >>= return . x
putX :: Int -> State Point ()
putX newVal = do
pt - get
put (pt { x = newVal })
increaseX :: State Point ()
increaseX = do
x - getX
putX (x + 1)
稍后我希望我能为 2 个类的层次结构实现 setter 和 getter,但现在我只想做这样的事情:
class A a where
putX :: Int -> State Point ()
instance A (State Point) where
putX newVal = do
pt - get
put (pt { x = newVal })
how can i group getX and putX in a class instance ?
the code below is an answer for this post Class set method in Haskell using State-Monad
import Control.Monad.State
data Point = Point { x :: Int, y :: Int } deriving Show
getX :: State Point Int
getX = get >>= return . x
putX :: Int -> State Point ()
putX newVal = do
pt - get
put (pt { x = newVal })
increaseX :: State Point ()
increaseX = do
x - getX
putX (x + 1)
Later I hope I will implement setters and getters for a hierarchy of 2 classes, but for now i just wanna do something like this:
class A a where
putX :: Int -> State Point ()
instance A (State Point) where
putX newVal = do
pt - get
put (pt { x = newVal })
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您似乎在这里混淆了多个概念,以至于我不确定您到底想要实现什么目标。关于您可能追求的一些想法:
字段访问,即一种检查或替换较大数据结构的方法。这实际上并不适合类型类,因为对于“内部字段”和“数据结构”的许多组合来说,可能有多个访问器。沿着这些思路的抽象通常称为“镜头”。
有状态引用。在
State
单子中的大部分情况下,这相当于将上述镜头之类的东西与标准get
和put
相结合。在这种情况下,您可以为特定 monad 和访问器数据类型的组合提供一个类型类,但它实际上不会做那么多。重载对特定字段的访问,以便函数可以处理包含“x”字段的任何数据类型。在这种情况下,我假设您还需要“y”,作为 2D 点的某种类型类。然而,这与上述问题完全不同。
也许你可以澄清你的目标?
You seem to be conflating multiple concepts here, to the point that I'm not sure exactly what you're aiming to accomplish. A few thoughts on what you might be after:
Field access, i.e., a way to inspect or replace a piece of a larger data structure. This doesn't really lend itself to a type class, because for many combinations of "inner field" and "data structure" there will be more than one accessor possible. Abstractions along these lines are often called "lenses".
Stateful references in some generic fashion. For the most part in a
State
monad this amounts to combining something like the aforementioned lenses with the standardget
andput
. In this case you could have a type class for the combination of a particular monad and the accessor data type, but it wouldn't really do that much.Overloading access to a particular field, so that functions can work on any data type that contains an "x" field. In this case I assume you'd also want "y", as some sort of type class for 2D points. This is entirely separate from the above issues, however.
Perhaps you could clarify your goal?