I have multiple savings accounts, some of which I want to partition into
mutiple virtual "subaccounts" that don't merit their own savings account. I
want to use org-mode tables to keep track how much money is each
subaccount. Given the following table:

#+TBLNAME: trans-150925
| ! | Amount | From       | To         | Subacct     |
|---+--------+------------+------------+-------------|
|   |     50 | Short Term | Inbox      | Bond        |
|   |    200 | Inbox      | Short Term | Bond        |
|   |    120 | Gifts      | Inbox      | Baby Gifts  |
|   |     75 | Short Term | Inbox      | Furnishings |

In this example, I have accounts "Inbox", "Short Term", and "Gifts". Of
these accounts, "Short Term" has two subaccounts "Bond" and "Furnishings",
and "Gifts" has a subaccount "Baby Gifts". I want to create a function that
given a subaccount name, calculates the net amount to be
withdrawn/deposited to the subaccount. Note that "Inbox" doesn't have any
subaccounts, which I want to use to determine if a given transaction is a
withdrawal or deposit to the subaccount.

I have created the following two functions to implement this:

(defun sbr/org-lookup-trans (category date s-name r-name)
  (let* ((table (concat "trans-" date))
         (s-range (format "@I%s..@>%s" s-name s-name))
         (s-col (org-table-get-remote table s-range))
         (r-range (format "@I%s..@>%s" r-name r-name))
         (r-col (org-table-get-remote table r-range)))
    (org-lookup-all category s-col r-col)))

(defun sbr/get-net-subacct (category date)
  (let* ((from-vec (sbr/org-lookup-trans category date "$Subacct" "$From"))
  (to-vec (sbr/org-lookup-trans category date "$Subacct" "$To"))
         (amount-vec (sbr/org-lookup-trans category date "$Subacct"
"$Amount"))
         (from-inbox-ind <indices of all from-vec elements that equal
"Inbox">) ; A
       (to-inbox-ind  <indices of all to-vec elements that equal "Inbox">)
; B
       (adds amount-vec[from-inbox-ind]) ; C
       (subs amount-vec[to-inbox-ind]))  ; D
    (calc-eval (if (zerop (length subs))
                 adds
 (concat adds "-" subs)))))

I need help filling in the pseudo code in lines A through D, namely:

1. how to get a list of all indices of elements in a vector that satisfy a
predicate?
2. how to reference a vector by a list of indices?

In this example the function should return the following values:

(sbr/get-net-subacct "Bond" "150925") ==> 150
(sbr/get-net-subacct "Furnishings" "150925") ==> -75
(sbr/get-net-subacct "Baby Gifts" "150925") ==> -120

How do I implement the above pseudocode functions? Is there a simpler way
to accomplish this task?

Reply via email to