tombh

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?

Showing Posts 16 to 7

tombh

tombh OP

That really helped clarify it for me, thank you :slight_smile:

peerreynders

peerreynders


Pattern matching‡ is the conditional construct - the case expression is just one way of utilizing it.

‡ Not to be confused with destructuring:

NobbZ

NobbZ

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

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

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:

defp select_item(items, idx) do
  case items do
    [{name, weight}|_] when idx < weight -> name
    [{_, weight} | tail] -> select_item(tail, idx - weight)
  end
end

But it is idiomatic to move such a case which 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 case is usually prefered of using if and some predicate functions and/or using getter functions.

LostKobrakai

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

tombh OP

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

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

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 Enum and Stream is by far the most idiomatic way dealing with lists and other “iterables”.

peerreynders

peerreynders

FYI:smile:

Of course, one should be able to implement some functions in Enum on their own (for lists at least). map , reduce , reverse , concat , those are my personal favorites …

When learning to a certain degree it can be helpful to make Enum off-limits until recursion (body and tail) is well understood - otherwise Enum can be come a crutch.

Where Next? Top

Trending in Questions Top

RSP87
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
kszambelanczyk
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
RemyXRenard
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
velrest
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
samoloth
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
nseaSeb
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
FlyingNoodle
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 Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
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
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
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
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews