Skip to content
Snippets Groups Projects
Valuation.hs 1.52 KiB
Newer Older
  • Learn to ignore specific revisions
  • chrg's avatar
    chrg committed
    {-# LANGUAGE BlockArguments #-}
    {-# LANGUAGE LambdaCase #-}
    
    module Data.Valuation (
      Valuation,
    
      -- * Constructors
      singleton,
      fromMap,
      fromPairs,
    
      -- * Destructors
      toMap,
      toPairs,
    
      -- * Access
      setTruthValue,
      truthValue,
      condition,
    
      -- * Helpers
      viaMap,
      viaMapF,
    ) where
    
    import Data.Functor.Identity
    import qualified Data.Map.Strict as Map
    
    newtype Valuation l = Valuation {toMap :: Map.Map l Bool}
    
    singleton :: (Ord l) => l -> Bool -> Valuation l
    singleton l t = fromMap $ Map.singleton l t
    
    viaMap :: (Map.Map l Bool -> Map.Map l Bool) -> Valuation l -> Valuation l
    viaMap fn = runIdentity . viaMapF (Identity . fn)
    
    viaMapF :: (Functor f) => (Map.Map l Bool -> f (Map.Map l Bool)) -> Valuation l -> f (Valuation l)
    viaMapF fn = fmap fromMap . fn . toMap
    
    fromMap :: Map.Map l Bool -> Valuation l
    fromMap = Valuation
    
    fromPairs :: (Ord l) => [(l, Bool)] -> Valuation l
    fromPairs = Valuation . Map.fromList
    
    toPairs :: Valuation l -> [(l, Bool)]
    toPairs = Map.toList . toMap
    
    truthValue :: (Ord l) => Valuation l -> l -> Maybe Bool
    truthValue (Valuation m) = (`Map.lookup` m)
    
    {- | Conditions a valuation with key value pair, if it conficts with the valuation,
    it returns Nothing
    -}
    condition :: (Ord l) => Valuation l -> l -> Bool -> Maybe (Valuation l)
    condition v l t =
      viaMapF
        ( Map.alterF
            \case
              Just t' | t' /= t -> Nothing
              _ -> Just (Just t)
            l
        )
        v
    
    setTruthValue :: (Ord l) => Valuation l -> l -> Bool -> Valuation l
    setTruthValue v l t = viaMap (Map.insert l t) v