[erlang-questions] If Condition vs. Multiple Function Clauses

Mahesh Paolini-Subramanya mahesh@REDACTED
Sat Jun 15 10:43:00 CEST 2013

Via LYSE and ROK - and with the forlorn hope that this doesn't start up again :-)  --> 

It may be more FAMILIAR, but that doesn't mean 'else' is a good thing. I know that writing '; true ->' is a very easy way to get 'else' in Erlang, but we have a couple of decades of psychology-of-programming results to show that it's a bad idea. I have started to replace:

	if X > Y -> a()		if X > Y  -> a()
	 ; true  -> b()		 ; X =< Y -> b()
	end		     	end

	if X > Y -> a()		if X > Y -> a()
	 ; X < Y -> b()		 ; X < Y -> b()
	 ; true  -> c()		 ; X ==Y -> c()
	end			end
which I find mildly annoying when _writing_ the code but enormously helpful when _reading_ it.

Speaking for myself, I've pretty much gotten to the point where I don't notice it.  
Heck, I barely notice syntax anymore.  About the best analogy I can come up with is spoken languages (adjectives after nouns in Italian? The Horror! The Horror!).  It may seem strange at first, but you don't even notice it after a few days…


Mahesh Paolini-Subramanya
That Tall Bald Indian Guy...
Google+  | Blog   | Twitter  | LinkedIn

On Jun 15, 2013, at 2:40 AM, Steve Davis <steven.charles.davis@REDACTED> wrote:

> I strongly (personally) dislike use of "if" syntax, but only because of the counterintuitive "true" evaluation.
> What if the language were to return the atom "else" instead of "true"?
> I doubt that would be considered "better" but it would sure make things more readable...
> /s
> On Friday, June 14, 2013 8:06:33 AM UTC-5, Lars Herbach wrote:
> Hi List,
> I'm currently working myself through the "Études for Erlang" book [1] and in exercise it wks's to write a recursive function, calculating the greatest common divisor for two numbers N and M. The suggested solution is a single gcd/2 function with an If condition and recursion:
> gcd(M, N) -> 
>     if M == N -> M;
>        M > N -> gcd(M - N, N;
>        true -> gcd(M, N - M)
>     end.
> I by myself took another way, working with multiple function clauses (did I name it right?):
> gcd(M, N) when M == N ->
>     M;
> gcd(M, N) when M > N ->
>     gcd(M - N, N);
> gcd(M, N) ->
>     gcd(M,  N - M).
> Now I've got two questions about that: 
> 1) Is my solution still recursive, since I practically call different functions?
> 2) Are there any benefits in regards of efficiancy for the first solution?
> Thanks,
> Lars.
> [1]: http://shop.oreilly.com/product/0636920030034.do
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20130615/b39e1dd2/attachment.htm>

More information about the erlang-questions mailing list