开发者

haskell state and typeclasses

开发者 https://www.devze.com 2023-03-10 11:07 出处:网络
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

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 })
 


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 standard get and put. 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?

0

精彩评论

暂无评论...
验证码 换一张
取 消