[erlang-questions] Feedback for my first non-trivial Erlang program

Aaron J. Seigo aseigo@REDACTED
Tue Dec 15 22:57:42 CET 2015


On Tuesday, December 15, 2015 01.45:26 Paul Wolf wrote:
> caBalance(T) -> caBalance(T-1) + salary(T-1) - expenses(T-1) -
> tradingFees(T-1).

https://en.wikipedia.org/wiki/Tail_call

this is going to create a stack of T calls to caBalance (let alone all the 
others) as it is not tail recursive.

by using an accumulator to build our result, the VM will be able to clear the 
call stack each time:

caBalance(T) when is_integer(T) -> caBalance(T, 0).
caBalance(0, Total) -> Total;
caBalance(T, Total) -> 
	caBlance(T - 1, Total + salary(T-1) - expenses(T-1) - tradingFees(T-1)).

or you could use a sequence and a fold:

caBalance(T) when is_integer(T) ->
	lists:foldl(fun(Month, Acc) -> 
				salary(Month) + expenses(Month) + tradingFees(Month) + Acc end, 
			0, lists:seq(1, T)).

there are a number of functions in your code that suffer from this, including 
profit/3, expenses/1.

on another note, as I've gotten more comfortable w/Erlang, I've found myself 
using case less and less and doing things like this:

trading_fees(T) -> trading_fees_when_working(T, working(T)).

trading_fees_when_working(T, true) ->
	investments(T) + transactionFee();
trading_fees_when_working(T, false) -> 
	trading_fees_when_working(T, true) + tax(expenses(T),T).

I find it easier to read such code as it expands and gets more complex, and in 
this case it makes it more evident that when working(T) == false, it is 
actually the same as when working but with taxes. readability ftw. but maybe 
that's just me :)

-- 
Aaron Seigo
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 198 bytes
Desc: This is a digitally signed message part.
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20151215/aad44035/attachment.bin>


More information about the erlang-questions mailing list