thousandsofthem

thousandsofthem

Trying to write good elixir code.

Input:

data = %{"a" => 0, "b" => 2, "c" => 0, "evilkey" => 666}

for specific keys i need to write some specific output if condition is true

Ruby version:

out = []
out << "text1" if data["a"] > 0
out << "text2" if data["b"] > 0
out << "text3" if data["c"] > 0
out

Ugly elixir version:

out = []
out = if data["a"] > 0 do
  out ++ ["text1"]
else
  out
end
...
...
out

Good elixir version: ???

Any thoughts here?

Showing Posts 1 to 10

taiansu

taiansu

A more functional apporach

output_texts = %{
  "a" => "text1",
  "b" => "text2",
  "c" => "text3",
}

out = data
      |> Enum.filter(fn {_, v} -> v > 0 end)
      |> Enum.filter(fn {k, _} -> Enum.member(Map.keys(output_texts), k) end)
      |> Enum.map(fn {k, _} -> output_texts[k] end)
      |> Enum.join()
michalmuskala

michalmuskala

You can do that by using if as an expression and assembling list of values finally concatenating them together:

IO.iodata_to_binary([
  if(data["a"] > 0, do: "text1", else: ""),
  if(data["b"] > 0, do: "text2", else: ""),
  if(data["c"] > 0, do: "text3", else: "")
])

You could even extract the if to a separate function, if the pattern if very repeating:

defp if_positive(value, text), do: if(value > 0, do: text, else: "")

IO.iodata_to_binary([
  if_positive(data["a"], "text1"),
  if_positive(data["b"], "text2"),
  if_positive(data["c"], "text3")
])
thousandsofthem

thousandsofthem OP

Thanks!

The solution with filters and map look about right.

Re: IO.iodata_to_binary thing - i can’t just put things together this way, but overall it looks good, just need to add |> Enum.filter(fn(x) -> !is_nil(x) end), i.e.

[
  (if data["a"] > 0, do: "text1"),
  (if data["b"] > 0, do: "text2"),
  (if data["c"] > 0, do: "text3")
] |> Enum.filter(fn(x) -> !is_nil(x) end)
benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe
data
|> Enum.filter(&match?({_, v} when v > 0, &1))
|> Enum.map(fn 
  {"a", _} -> "text1"
  {"b", _} -> "text2"
  {"c", _} -> "text3"
end)
benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

Also because nobody has mentioned this yet, the “ugly elixir version” is not actually an elixir version. It would not work at all because out is immutable.

thousandsofthem

thousandsofthem OP

It will, there are re-assignment for out:

out = if ...
  out ++ ...
else
  out
end

so every consequent out is different variable

NobbZ

NobbZ

We do not have any guarantee of ordering in a map. So in theory the begs pour of this snippet is non deterministic, while in the OPs version we do have an explicit ordering of the keys and their transformation/concatenation into the result.

rvirding

rvirding

Creator of Erlang

I know people love |> but you don’t have to use it:

:maps.fold(fn (k,v,acc) when v > 0 -> acc ++ [output_texts[k]]
              (_,_,acc) -> acc
           end, [], data)

There is probably a function equivalent to fold in Enum but it is called something else and I could not immediately see it, hence using the one in :maps.

thousandsofthem

thousandsofthem OP

Yeah, in my use-case ordering guarantees are required so maps don’t work (but for someone else it could be better approach). also there are other non-related keys as well (which should be filtered out)

plain [..., ..., ...] |> remove nils works just fine - ordering granaries, short and easy to read code

NobbZ

NobbZ

It’s called reduce and is a left fold AFAIR

Where Next? Top

Trending in Questions Top

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
Blokh
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
roeland
Kia ora, We have been using elixir-google-api to connect to Google Drive. However, with the updates to Tesla due to CVEs this is now bro...
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
Onor.io
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
jaybe78
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
Trolleger
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

Other Trending Topics Top

garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
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
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
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
wintermeyer
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

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews