niels_bom
While learning Elixir I’ve been writing and rewriting some practice functions. Some of the rewriting was to ensure recursive functions are tail-call-optimized (TCO) or to prevent expensive operations like concatenating lists or Enum.count(list).
(and yes mr Knuth I know about premature optimization being bad)
Some things I’ve noticed myself doing while rewriting functions is:
- naming: for public function
fooname the corresponding private function_foo - the private functions often have an extra parameter (so I can prepend to list for TCO)
- prepended result lists are reversed before they’re returned
- in public function heads pattern match for simple cases (as I can often do that without the need for the extra parameter used in the private function)
And I’d like to get some feedback on whether what I’m doing is idiomatic/common practice.
My code is here: Practicing Elixir · GitHub
Just $ elixir bla.exs to run the tests.
Thanks!
Trending in Questions
Hey guys,
I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly
Do you guys have any suggestions what is the best prac...
New
Hello!
Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app.
I creat...
New
I have what I’ve heard referred to as a “lookup table” in my database. This is a way of assigning codes to common values. One common lo...
New
Hello,
I’m developing a online persistent chat system (what’s app) like using elixir/dynamodb/aws for a mobile app(flutter).
The diffic...
New
What approach to take when sending live updates to “random” users Hi! I have a question, I have a little chat app, and when I create a DM...
New
Anyone here using Honeybadger?
My Honeybadger account is being overwhelmed with noise from some bots. Seeing a lot of
Bandit.HTTPError...
New
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
Other Trending Topics
Hobbes is a low-level distributed database for the Elixir programming language.
Hobbes provides a simple, safe, and scalable storage lay...
New
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve.
They are GUI (Emerge) and State management (S...
New
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
There are three potential reasons for members of this forum to have a look at https://vutuv.de
You are tired or annoyed of LinkedIn.
Yo...
New
Aludel - LLM Evaluation Workbench
Aludel is an embeddable Phoenix LiveView dashboard for evaluating and comparing LLM prompts across mult...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #blog-post
- #elixir-ls
- #ai
- #elixirconf-us
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #hex
- #security
- #metaprogramming










Showing Posts 1 to 10- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
blatyo
From what I’ve seen in other Elixir and Erlang code, it’s typical to name the private functions
do_blahwhen it’s an implementation detail ofblah. Since it’s private, it shouldn’t matter much what you choose though. I think it’s more important that it’s near he public function.Very common for TCO. The extra argument is typically called the accumulator. It’s also a hint that you can turn most recursive operations into a form of reduce to make them TCO.
If it’s my own private code, I sometimes don’t bother with splitting the functions and just pass the accumulator as an optional argument with a default. For example, your faster filter could be defined like this:
That’s common. Doing the work in order during recursion can easily recreate an entire list multiple times while prepending to the head is O(1).
Yes, this is a good practice. If you validate at your boundary it means all subsequent code can ignore bad values.
Qqwy
Most of what you are doing is indeed idiomatic/common.
do_foois more common than_foobut since these are private, internal functions anyway there is no real problem in naming them anything else, since they can always be renamed later without problems.I disagree with @blatvo about ‘just passing the accumulator as default’. I think it is bad style (because it exposes an implementation detail the rest of the world) and I would advise against it, even in your own personal code.
I do have a comment on your code example. Most notably in
ffilter, you write an inline if-statement:I think that the following is more readable (and therefore, arguably, more idiomatic):
And as an aside: Is there a reason you used comments rather than
@documentation in your example code?Oh, and another interesting fact about tail-call recursive functions about enumerables, which I don’t think Elixir itself currently does, is that those reversal steps are only required if the next step of a sequence of enumeration-manipulations requires that order. In other words: If something does not rely on the order we can postpone the reverse, or maybe even skip it all-together. (Such as:
some_list |> Enum.filter only_nice_elements |> Enum.count.I know Haskell has a set of (very complicated and fiddly…) compiler rewrite-pragmas to optimize common cases of this.
peerreynders
Is
do_fooactually common for tail recursive implementations though?Ultimately functions are not identified by name - they are identified by the combination of name and arity i.e.
foo/1andfoo/2are already different functions. Adopting eitherdo_fooor_foois equivalent to going down the Hungarian Notation rabbit hole - (many people would argue that if you need type/protection hints then use an IDE rather than burying that information in the function name).So I’m more familiar with the
foo/1andfoo/2convention to highlight that these distinct functions are part of the same functionality behind thefooname.I think there is some conflation going on here.
Being tail recursive and having private access is orthogonal. They may coincide with your choice of implementation. Alternately in Erlang it’s the public function that has to be exported i.e. all functions are private by default.
That “extra parameter” tends to be a differentiator between implementing body or tail recursion.
Edit: Changed “stack of intermediate results” to “bag of intermediate results” i.e. holder of intermediate data with whatever internal structure is appropriate to solving the problem.
blatyo
Not defending the usage, as I sort of dislike
do_, but if you search fordo_in these examples, it at least seems like a pattern.https://github.com/elixir-lang/elixir/blob/v1.8.1/lib/elixir/lib/list.ex
https://github.com/erlang/otp/blob/master/lib/stdlib/src/lists.erl
While you could technically have a public
foo/1and a privatefoo/2, there are cases where you want the public interface to have afoo/2arity as well, but still need a private function for implementation details. I personally prefer some convention to separate the name of the public interface from the implementation detail.peerreynders
In the Elixir source there does seems to be a tendency to use
do_prefix for private functions. The question is whether it should be considered idiomatic when it isn’t mentioned in the naming conventions or style guide.Due to already established conventions for leading underscores,
_fooprobably isn’t the greatest choice for a function name.In the Erlang source
do_flatten/2seems more like an escape asflatten/2was needed for export.Qqwy
No: It is common for private functions, which tail-recursive implementation functions often are. The
. 
do_*prefix is not the only one used, but definitely the most common, and the one adopted by e.g. the standard library.EDIT: Above was written before seeing your last response. You are completely astute that this convention is not in the style guide and that other naming schemes are ‘just as good’. As well as that starting function names with a leading underscore is a BadIdea
In many of the simpler cases, a tail-recursive solution does not need this ‘extra’ stack. But even if we have this extra parameter, there are many cases in which an accumulator is not a stack: Only when talking about linked lists (which are essentially stacks) will we end up with accumulators that are lists/stacks. (Of course there are other enumerables that would like to be transformed into a list and back during enumeration, but there are other enumerables, like trees, for which this is not the case).
clinton
I picked up the
defp _foo()naming convention from one of Dave Thomas’s books and I prefer it todefp do_foo()because havingdo_in front of every private function name makes my private function area look like a sea of meaninglessdo_s and it is harder for me to read quickly.I also prefer the underscore convention over
defp foo()because the underscore makes my code more readable by letting me know in-line that the_foo()function is private and located in the current file. I don’t have to go look for the function definition and figure out where it came from. I instantly know at a glance.The other nice thing about using
defp _foo()for private functions is that underscored function names are not imported into other files. So, if I make_foo()a public function so I can fiddle with it iniexand then forget to make it private again, it still won’t get imported into other modules and accidentally used.l00ker
This is what I do as well for exactly the same reasons. Using the
_foo()convention quickly tells me that the function is defined within the same module and not an imported function from another module.If you use
def _foo(), as you mentioned, it is basically hidden from TAB completion iniexetc., but remains callable from outside the module if you know it’s there. It acts like the Reflection functions inEcto.Schema- i.e.__schema__(:fields)etc.Maybe it’s not for everyone, but I’ve found it to be quite useful. I’m glad someone else sees it that way as well
wolf4earth
One thing of note is that tail-recursive functions are not strictly faster or more efficient than their body-recursive counterparts.
@PragTob wrote quite an interesting piece on that a while ago:
With a follow up here:
kwando
This is also mentioned in the Erlang documentation
https://erlang.org/doc/efficiency_guide/myths.html