Functor
Functor

Reputation: 610

Mutable field structure in Haskell without Lens

I want to write a function that generates a structure that has fields of mutable values.

Originally, I wrote in TypeScript and the code is as follows:

const Foo = <A>(a: A) =>
  ({
    x: a,             //mutable
    y: someFunction   //mutable
  });

Basically, the type of x is always A, and y is A -> A even they are mutable.

I just need a simple setter and getter function to mutate the fields, and preferably want to use just ST-monad and don't want to depend on libraries such as Lens.

The closest thing I've found so far is ST mutable array Data.Array.MArray, but this one is for arrays not structures.

What is simple smart approach do you recommend?

Upvotes: 1

Views: 131

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477607

If you define a structure like:

data Foo a = Foo {
    bar :: a,
    qux :: a -> a
}

then you can for example define an object:

myFoo :: Foo Int
myFoo = Foo 2 id

and create a slighlty modified copy with:

myFoo2 :: Foo Int
myFoo2 = myFoo { bar = 4 }

so you can use that in an STRef to work with a reference that is updated then with modifySTRef, for example:

myST :: ST s (Foo Int)
myST = do
    ref <- newSTRef (Foo 2 id)
    modifySTRef ref (\x -> x { bar = 4 })
    readSTRef ref

and you can thus run this with runST myST. We can for example print the bar after evaluating the ST s (Foo Int):

ghci> print (bar (runST myST))
4

Upvotes: 2

Related Questions