Skip to content

Instantly share code, notes, and snippets.

@3v0k4
Last active December 21, 2019 00:17
Show Gist options
  • Select an option

  • Save 3v0k4/72004863c84aa1cbfcf2443b8e337930 to your computer and use it in GitHub Desktop.

Select an option

Save 3v0k4/72004863c84aa1cbfcf2443b8e337930 to your computer and use it in GitHub Desktop.

Revisions

  1. 3v0k4 revised this gist Dec 21, 2019. No changes.
  2. 3v0k4 created this gist Mar 18, 2019.
    47 changes: 47 additions & 0 deletions Main.purs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,47 @@
    data Transaction
    = Deposit Info
    | Withdraw Info

    derive instance eqTransaction :: Eq Transaction

    instance showTransaction :: Show Transaction where
    show (Deposit i) = show i
    show (Withdraw i) = show i

    type Info =
    { timestamp :: DateTime
    , amount :: Int
    }

    deposit :: forall m. Monad m => m DateTime -> Int -> StateT (Array Transaction) m Unit
    deposit nowDateTime amount = do
    ts <- lift nowDateTime
    let t = Deposit { timestamp: ts, amount: amount }
    modify_ \ts -> ts <> [t]

    withdraw :: forall m. Monad m => m DateTime -> Int -> StateT (Array Transaction) m Unit
    withdraw nowDateTime amount = do
    ts <- lift nowDateTime
    let t = Withdraw { timestamp: ts, amount: amount }
    modify_ \ts -> ts <> [t]

    printStatement :: forall m. Monad m => (String -> m Unit) -> StateT (Array Transaction) m Unit
    printStatement logger = do
    s <- gets toStatement
    lift $ logger s

    toStatement :: Array Transaction -> String
    toStatement =
    fst <<< foldl fnc (Tuple "" 0)
    where
    fnc (Tuple s i) (Deposit d) =
    Tuple (s <> "\n" <> joinWith " " [ show d.timestamp, show d.amount, show $ i + d.amount]) (i + d.amount)
    fnc (Tuple s i) (Withdraw w) =
    Tuple (s <> "\n" <> joinWith " " [ show w.timestamp, "-" <> show w.amount, show $ i - w.amount]) (i - w.amount)

    main :: Effect Unit
    main = do
    flip evalStateT [] do
    deposit nowDateTime 500
    withdraw nowDateTime 100
    printStatement log