ahmadferdous

ahmadferdous

I have structs Company, Employee and a list of struct values employees. Struct Employee contains 2 fields - hours and bill.

I need to know total hours and total bill. Should I iterate once (for loop?!) to calculate both together or should we do the following? One of my colleagues say the following is Elixir-y. Why is iterating multiple times encouraged when it is inefficient?

I’m sure there is a good reason and I want to know. Please help me.

def calculate(company) do
    company
    |> calculate_total_hours()
    |> calculate_total_bill()
end

def calculate_total_hours(company) do
  total = company.employees
  |> Enum.map(& &1.hours)
  |> Enum.sum()

  %{company | total_hours: total}
end

def calculate_total_bill(company) do
  total = company.employees
  |> Enum.map(& &1.bill)
  |> Enum.sum()

  %{company | total_bill: total}
end

EDIT: Updated code

Showing Posts 1 to 10

al2o3cr

al2o3cr

Because it’s easier to read operations that are cleanly decomposed into smaller parts, and because “inefficient” is relative. Traversing a list is a very cheap operation on the BEAM (it’s almost a Lisp under the hood).

It’s hard to say more about the specific example since it doesn’t work: calculate_total_hours returns a number but is piped into a function that expects a list, and it’s unclear where the total hours and total bill should be stored in company.

aenglisc

aenglisc

“Make it work, then make it beautiful, then if you really, really have to, make it fast. 90 percent of the time, if you make it beautiful, it will already be fast. So really, just make it beautiful!”

gregvaughn

gregvaughn

I would likely write this as a single reduce, and I don’t think it suffers elixir-y-ness

{total_hours, total_bill} =
  Enum.reduce(company.employees, {0, 0}, fn %{hours: h, bill: b}, {h_acc, b_acc} ->
    {h_acc + h, b_acc + b}
  end)
10
Post #3
ahmadferdous

ahmadferdous OP

Thanks. I made up the example and the code was not correct. Sorry about that. Updated.

ahmadferdous

ahmadferdous OP

I made up the example to capture the problem. Sorry that it was not a working code. I updated code.
The question remains the same - why iterate twice when I can achieve the same goal by iterating just once? In future, what should I answer when somebody coming from OOP background asks me?

jswny

jswny

Why not just use streams? They are lazy so as long as you only call Stream functions, you can chain many operations together and only evaluate them at the end for a single iteration. You can keep the multiple functions calls so you don’t have to mash them into one, and you can still iterate only once. Take a look at the paragraphs at the top of the Stream docs for a very similar example: Stream — Elixir v1.20.2

ahmadferdous

ahmadferdous OP

@jswny , each operation (calculate_total_hours and calculate_total_bill) needs to be evaluated. So, these 2 operations do not seem to be streamable.

kokolegorille

kokolegorille

I am curious how You would make it in one go…

If You have those 2 ways to solve this problem, use Benchee to check the speed of both. You might be surprised by the result :slight_smile:

UPDATE: I fixed the repo path, I was not on the right tab :man_facepalming:

tomkonidas

tomkonidas

ahmadferdous

ahmadferdous OP

@kokolegorille , see @gregvaughn’s answer above that uses a single reduce function to calculate both in one go.

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
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
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
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
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

JesseHerrick
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
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
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
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

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews