1 module Symantic.Compta.Calc.Flow where
3 import Control.DeepSeq (NFData)
6 import Data.Functor (Functor)
7 import Data.Maybe (Maybe(..))
8 import Data.Ord (Ord(..))
9 import GHC.Generics (Generic)
10 import Text.Show (Show(..))
12 import Symantic.Compta.Lang
15 -- | A 'Flow keeps track separatly of what goes 'In'
16 -- and what goes 'Out' of an account.
21 deriving (Eq, Show, Generic, NFData, Functor)
23 instance FromInteger qty => FromInteger (Flow qty) where
24 fromInteger i | i <= 0 = Out (fromInteger i)
25 | otherwise = In (fromInteger i)
27 flowIn :: Flow a -> Maybe a
33 flowOut :: Flow a -> Maybe a
39 flow :: Flowable a => a -> Flow a
41 case (outOf f, inOf f) of
42 (Just o, Nothing) -> Out o
43 (Nothing, Just i) -> In i
44 (Just o, Just i) -> Bidir o i
45 (Nothing, Nothing) -> Bidir f f
46 unFlow :: Addable a => Flow a -> a
52 instance Zeroable a => Zeroable (Flow a) where
54 instance (Nullable a, Addable a) => Nullable (Flow a) where
58 Bidir o i -> null (o + i)
59 instance Addable a => Addable (Flow a) where
60 In i + Out o = Bidir o i
61 In ix + In py = In (ix + py)
62 In i + Bidir ny py = Bidir ny (i + py)
64 Out ox + Out ny = Out (ox + ny)
65 Out o + In i = Bidir o i
66 Out ox + Bidir ny i = Bidir (ox + ny) i
68 Bidir ox ix + Out o = Bidir (ox + o) ix
69 Bidir ox ix + In py = Bidir ox (ix + py)
70 Bidir ox ix + Bidir ny py = Bidir (ox + ny) (ix + py)
71 instance Negable a => Negable (Flow a) where
73 In i -> Out (negate i)
74 Out o -> In (negate o)
75 Bidir o i -> Bidir (negate i) (negate o)
76 instance Flowable (Flow a) where
80 Bidir n _ -> Just (Out n)
84 Bidir _ p -> Just (In p)
88 class Flowable a where
92 instance Flowable Decimal where
101 instance Flowable a => Flowable (Map k a) where
103 case Map.mapMaybe inOf q of
104 m | Map.null m -> Nothing
107 case Map.mapMaybe outOf q of
108 m | Map.null m -> Nothing
110 instance Flowable a => Flowable (k, a) where
111 inOf (u, q) = (u,) <$> inOf q
112 outOf (u, q) = (u,) <$> outOf q