1 module Literate.Accounting.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 Literate.Accounting.Math
13 import Literate.Accounting.Rebindable
16 -- | A 'Flow keeps track separatly of what goes 'In'
17 -- and what goes 'Out' of an account.
22 deriving (Eq, Show, Generic, NFData, Functor)
24 instance FromInteger qty => FromInteger (Flow qty) where
25 fromInteger i | i <= 0 = Out (fromInteger i)
26 | otherwise = In (fromInteger i)
28 flowIn :: Flow a -> Maybe a
34 flowOut :: Flow a -> Maybe a
40 flow :: Flowable a => a -> Flow a
42 case (outOf f, inOf f) of
43 (Just o, Nothing) -> Out o
44 (Nothing, Just i) -> In i
45 (Just o, Just i) -> Bidir o i
46 (Nothing, Nothing) -> Bidir f f
47 unFlow :: Addable a => Flow a -> a
53 instance Zeroable a => Zeroable (Flow a) where
55 instance (Nullable a, Addable a) => Nullable (Flow a) where
59 Bidir o i -> null (o + i)
60 instance Addable a => Addable (Flow a) where
61 In i + Out o = Bidir o i
62 In ix + In py = In (ix + py)
63 In i + Bidir ny py = Bidir ny (i + py)
65 Out ox + Out ny = Out (ox + ny)
66 Out o + In i = Bidir o i
67 Out ox + Bidir ny i = Bidir (ox + ny) i
69 Bidir ox ix + Out o = Bidir (ox + o) ix
70 Bidir ox ix + In py = Bidir ox (ix + py)
71 Bidir ox ix + Bidir ny py = Bidir (ox + ny) (ix + py)
72 instance Negable a => Negable (Flow a) where
74 In i -> Out (negate i)
75 Out o -> In (negate o)
76 Bidir o i -> Bidir (negate i) (negate o)
77 instance Flowable (Flow a) where
81 Bidir n _ -> Just (Out n)
85 Bidir _ p -> Just (In p)
89 class Flowable a where
93 instance Flowable Decimal where
100 _ | q <= 0 -> Nothing
102 instance Flowable a => Flowable (Map k a) where
104 case Map.mapMaybe inOf q of
105 m | Map.null m -> Nothing
108 case Map.mapMaybe outOf q of
109 m | Map.null m -> Nothing
111 instance Flowable a => Flowable (k, a) where
112 inOf (u, q) = (u,) <$> inOf q
113 outOf (u, q) = (u,) <$> outOf q