Haskell - How would I run a list of state monads?

I'm a little new to Haskell and I have problems with the state monad.

I have created the following types. Stat ahas an instance of a monoid, functor, applicative and monad created for him.

The "main" type in my program is the creature, and it has many arguments:

data Creature = Creature {
    strength  :: Stat Integer,
    dexterity :: Stat Integer,
    ...
}

data Stat a = Stat {
    modifiers :: [StatModifier],
    stat      :: a
}

data StatModifier = StatModifier {
    modifierType :: ModifierType,
    value        :: Integer
}

data ModifierType = 
  Enhancement
  | Morale
  | ...

There are many things that can happen to a creature. I decided to introduce these things with the state monad:

anyPossibleChange :: State Creature Creature

This can be damage to the creature, an increase in the strength of the creature, basically anything. The possibility of something made me think that the state monad was a good choice here. I agree with the creature in this initial state, make some modification and return my original state and new state in the tuple.

:

Creature {
    strength = Stat [] 10,
    dexterity = Stat [] 10
}

:

Creature {
    strength = Stat [StatModifier Enhancement 2] 10,
    dexterity = Stat [StatModifier Enhancement 4, StatModifier Morale 2] 10
}

, , .

, , . , .

applyChanges :: Creature -> [State Creature Creature] ->  Creature

, , , FoldM, .

?

+4
1

State Creature Creature . , , , ! ... applyChanges.

, , - Creature -> Creature, , , , :

applyChanges :: [Creature -> Creature] -> Creature -> Creature
applyChanges = foldr (.) id
+4

Source: https://habr.com/ru/post/1677956/


All Articles