tombh
I’m new to Elixir, and relatively new to functional programming. I’ve just written this little algorithm to take a weighted sample from a list of tuples;
# items = [apples: 10, oranges: 30, bananas: 60]
defp weight_based_choice(items) do
max = sum_weights(items)
state = %{
current: 0,
choice: nil,
random_value: Enum.random(1..max)
}
Enum.reduce(items, state, fn item, state ->
weight = elem(item, 1)
state = %{state | current: state[:current] + weight}
choice =
if(state[:random_value] <= state[:current]) do
elem(item, 0)
else
nil
end
if state[:choice] == nil && choice != nil do
%{state | choice: choice}
else
state
end
end)[:choice]
end
defp sum_weights(items) do
Enum.reduce(items, 0, fn item, acc ->
weight = elem(item, 1)
acc + weight
end)
end
Are there more idiomatic ways to do this?
Trending in Questions
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
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’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
So my question is quite simple and i have found no conclusive answer on forum, google or AI.
Should we use :erlang.float for Integer to ...
New
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
Hello,
I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New
Other Trending Topics
I am happy to introduce the very α version of the new programming language compiled to BEAM.
Welcome Cure.
It has literally three kille...
New
Hi there! We created Gust: A task orchestrator inspired by Airflow.
For those who have never heard about Aiflow, it’s a Python-based wor...
New
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
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
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #library
- #deployment
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #podcasts
- #javascript
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixirconf-us
- #ai
- #blog-post
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #hex
- #security
- #metaprogramming










Showing Posts 16 to 7- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
tombh
That really helped clarify it for me, thank you
peerreynders
Pattern matching‡ is the conditional construct - the case expression is just one way of utilizing it.
‡ Not to be confused with destructuring:
Kernel.destructure/2NobbZ
I’m not sure if elixir does this already, but yes, at least for the core-erlang representation it is necessary to do so, as core erlang only has single clause functions IIRC.
LostKobrakai
Not only semantically. Afaik the compiler does take functions with many function heads and makes them be a single function with a case statement inside.
NobbZ
As @LostKobrakai already pointed out, both do the same thing. They select the item from the list of items.
The multiheaded function you see there, has nothing to do with “differentiating functions by arity”, in fact, nothing is differentiated there, both are the same function, as both have the same name and the same arity.
What though I do use there is “pattern matching”, something very important to learn and understand when writing elixir.
To be honest, those 2 function clauses are semantically equivalent with the following single-clause function:
But it is idiomatic to move such a
casewhich matches on an argument directly and spans the full function body into a multi clause function.Also in general pattern matching in the functions head or a
caseis usually prefered of usingifand some predicate functions and/or using getter functions.LostKobrakai
I’d say both select an item. So they’re doing the same job. Just some inputs might recurse a few more times than others to get to an answer.
tombh
Thank you so much everyone! This is way more than I expected. It’s a lot to digest, I’ve learned so much. I like @gregvaughn’s suggestion the most, not because of the struct idea, but because it seems to me to realise the thought process in my original approach, except without all the noobish bloat. The struct idea is also fascinating as well of course.
A quick question about differentiating functions by arity, like this:
This of course seems to be quite idiomatic, but I’m struggling with reaching for it myself. I just feel that if a function does something different it should have a different name. Perhaps naively I think it’s better to make the condition explicit in say a case statement, and then call out to differently named functions just so that the intent of the code becomes more intuitive. Thoughts?
dimitarvp
I side with you. I see @peerreynders’s point but I’ve done my exercises and re-implemented most of
Enum.For such problems, start with idiomatic Elixir code and only go for hand-rolled algorithms if performance is of utmost importance.
NobbZ
Yes. I sign this. During learning you are totally correct.
But the question was about idiomatic code, not what would I write when I learn about recursion. And using
EnumandStreamis by far the most idiomatic way dealing with lists and other “iterables”.peerreynders
FYI …
When learning to a certain degree it can be helpful to make
Enumoff-limits until recursion (body and tail) is well understood - otherwiseEnumcan be come a crutch.