thousandsofthem

thousandsofthem

Writing idiomatic Elixir code

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?

Marked As Solved

thousandsofthem

thousandsofthem

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)

Also Liked

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")
])
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)
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()
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

It will, there are re-assignment for out:

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

so every consequent out is different variable

Where Next?

Popular in Questions Top

Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New

Other popular topics Top

yurko
Here are few pieces of (common) Linux knowledge that we use for reasonably small one server apps. We use Ubuntu but this should work for ...
New
peerreynders
Manning 2016 Halloween weekend sale via Deal of the Day Friday, October 28 - Half off all MEAPs - code WM102816LT Saturday, October 29 ...
326 29600 154
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New

We're in Beta

About us Mission Statement