15
\$\begingroup\$

Does anybody have tips for golfing in Erlang? I'm looking for specific things that can be applied to Erlang, not any language. I know we already have tips for Elixir, but that is different.

As usual, please post separate tips in separate answers.

Martin Ender
198k67 gold badges455 silver badges998 bronze badges
asked May 15, 2016 at 15:15
\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

Use the ending conditions

Suppose you have a function reversing a list:

r([H|T])->[T]++r(H);r([])->[].

Since this is the only condition left, this can be golfed into:

r([H|T])->r(T)++[H];r(_)->[].

Or, since this is an identity function:

r([H|T])->r(T)++[H];r(I)->I.

You can also abuse the wild-cards in if statements. E.g.

if A<B->A;true->B end.

This can be golfed into:

if A<B->A;_->B end.
answered Mar 19, 2020 at 7:27
\$\endgroup\$
1
\$\begingroup\$

Use Built-in Functions (BIFs)

Erlang’s built-ins like length/1, hd/1, tl/1, and arithmetic operators (+, -, *, div, rem) are concise. Prefer them over manual implementations. For example, hd(L) is shorter than [H|_]=L,H.

Use Guards Sparingly

Guards can shorten logic, but they add characters. Only use them if they replace a longer construct. For example:

f(X)when X>0->1;f(_)->0.

is concise if it avoids a case.

String Handling

Erlang strings are lists of integers, so use [C] for single characters (e.g., $a for 97) to save space over quoted strings. For example:

f()->$a.

is shorter than:

f()->"a".
answered Feb 23 at 11:18
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.