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 having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
Documentation
While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
Hello,
I’m trying to build a basic Phoenix web-app, and I’d like to use Tailwind.
However, when I launch mix phx.server, I get an error...
New
Hi everyone,
I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding.
I sta...
New
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
I’m working on a small exercise involving update_in/3, and I came up with this solution:
data = %{
name: "Periodic Table",
category:...
New
I’ve got trouble wrapping my head around the order in which functions are called in this snippet (from Phoenix’s authentication):
toke...
New
Other Trending Topics
Edit: 2026 May 15 - This post is archived.
Mob is alive!!
Main docs: mob v0.7.11 — Documentation
A bit of explanation for the slightly c...
New
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
I am happy to introduce the very α version of the new programming language compiled to BEAM.
Welcome Cure.
It has literally three kille...
New
Hobbes is a low-level distributed database for the Elixir programming language.
Hobbes provides a simple, safe, and scalable storage lay...
New
Hi everyone!
The first release candidate for the Expert language server project is now available!
We’ve published a press release detai...
New
A little off-topic, but I feel like people here have a good head on their shoulders.
I used to be quite good at making software. Was luc...
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
- #ai
- #ecto-query
- #elixirconf-us
- #blog-post
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #elixirconf-eu
- #api
- #forms
- #metaprogramming
- #hex











Showing Posts 1 to 10- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
peerreynders
Welcome to the forum!
Not necessarily idiomatic, just a different way of doing things:
NobbZ
Can’t we write
select_item/3roughly like this, making it effectively aselect_item/2?While also making use of
Enum.reduce/3insum_weights/2we can make it asum_weights/1:Then we leave
weight_based_choicenearly untouched (only adjusting calls to the functions we changed):This is probably one of the most idiomatic approaches. We could even implement
select_item/2in terms ofEnum.reduce_while/3, but usually this doesn’t add much in terms of readability, also not many people are used to that function…PS: Perhaps we need to adjust
</<=/>/>=in the guards… I’m writing this mostly freehand…peerreynders
So
or
People tend to have familiarity with
reducefrom other languages - when learning I feel that resorting toEnumimmediately is like heading straight for the power-tools even for the smallest job. To a certain degree choosing reduce when a simple recursive function will do feels a bit like “premature pessimization” especially as recursion is how iteration is accomplished in Elixir/Erlang - but I know I’m in the minority there.gregvaughn
That’s a fun little problem. Here’s my take, from playing around in iex
I believe this is the first time I’ve used
Enum.scan. It lets us get thataccumulated_weightsformat, which is handy for reuse if we will be getting more random samples from the same list of inputs.We get our
maxby pattern matching on the last item of accumulated_weightsEnum.reduce_whilethen halts iteration when it has found the proper match. It might make some static type people twitch because when continuing the random_value is kept as the accumulator, but when halting, the keyword becomes the accumulator that is returned from the overall iteration.gregvaughn
If I were to really use this in production, I’d likely wrap it in its own struct module like this:
Which could then be used in calling code like
This represents a pattern I’ve found myself favoring lately. Create an optimized data structure for the sorts of functions you will want to use on it. The calling code then has a 2 step process: 1) create the struct, 2) call the function. This may seem unnecessary, but you can unit test step 1 easily since there are no side effects (or randomness).
Plus, having a struct allows you to participate in Protocols. I could imagine
WeightedListimplementingInspectand perhaps evenCollectableif it’s an important enough part of your system.Edited to use
Enum.find_valueinstead ofEnum.reduce_whilewhich I find clearer for this situationNobbZ
I do see it quite the opposite.
reduce/foldor however you might call it, is a well understood pattern in FP, using it should happen from the muscle memory.Directly writing out the recursion though, is in my opinion not as readable as a clearly named
reduce. To do the reverse mapping, I have to understand the full recursive function to see, whether it reduces a list to a single value, if it maps a function over the list, or does even flatten things out on the way…With
Enum.xI clearly see the intend.Also, as remote calls are more expensive than local ones on the BEAM, writing out the recursion is actually the optimisation…
Of course, one should be able to implement some functions in
Enumon their own (for lists at least).map,reduce,reverse,concat, those are my personal favorites…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.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”.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.
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?