views:

350

answers:

4

I've been trying to learn Erlang and have been running into some problems with ending lines in functions and case statements.

Namely, when do I use a semicolon, comma, or period inside my functions or case statements?

I've gotten stuff to work, but I don't really understand why and was looking for a little more information.

+13  A: 

Comma at the end of a line of normal code.
Semicolon at the end of case case statement, or if statement, etc. The last case or if statement doesn't have anything at the end. A period at the end of a function.

example (sorry for the random variable names, clearly this doesn't do anything, but illustrates a point):

case Something of 
    ok ->
        R = 1,     %% comma, end of a line inside a case 
        T = 2;     %% semi colon, end of a case, but not the end of the last
    error ->
        P = 1,     %% comma, end of a line inside a case
        M = 2      %% nothing, end of the last case
end.               %% period, assuming this is the end of the function, comma if not the end of the function
marcc
Makes it clearer! Thanks!
samoz
You also use the semicolon at the end of a function clause which doesn't end the function (you end a function by using a dot, as marcc explained).
Adam Lindberg
you end a named function with a dot. Anonymous functions are terminated with an end keyword. Also you use dots after -include() and -compiler directives. It's best to think of the period as a final terminator. This is the "END" where as the comma and semicolon 's are seperators. As chthulahoops below says. the comma works as a seperator of a series, and the semicolon works a seperator for alternatives. , = and = or is a pretty decent way to remember.
Jeremy Wall
+2  A: 

You can think of it like english punctuation. Commas are used to separate things in a series, semicolons are used to separate two very closely related independent clauses[1] (e.g. the different cases of the case statement, function clauses of the same name and arity that match different patterns), and periods are used to end a sentence (complete thought).

  1. Or to prove you went to college. "Do not use semicolons. They are transvestite hermaphrodites representing absolutely nothing. All they do is show you've been to college." -- Kurt Vonnegut
Ben Hughes
Love the Vonnegut quote! I'll make sure to accent my usage of semi-colons; they really should be used more.
samoz
+4  A: 

I like to read semicolon as OR, comma as AND, full stop as END. So

foo(X) when X > 0; X < 7 ->
    Y = X * 2,
    case Y of
        12 -> bar;
        _  -> ook
    end;
foo(0) -> zero.

reads as

foo(X) when X > 0 *OR* X < 7 ->
    Y = X * 2 *AND*
    case Y of
        12 -> bar *OR*
        _  -> ok
    end *OR*
foo(0) -> zero *END*

This should make it clear why there is no ; after the last clause of a case.

cthulahoops
+1  A: 

The comma separates expressions, or arguments, or elements of a list/tuple or binary. It is overworked.

rvirding