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

Where Next?

Popular in Questions Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
JulienCorb
I am trying to implement my new.html.eex file to create new posts on my website. new.html.eex: &lt;h1&gt;Create Post&lt;/h1&gt; &lt;...
New
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; someth...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
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
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New

Other popular topics Top

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
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30840 112
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 53578 245
New
RisingFromAshes
I've read in another post that it may be possible with a router helper - but I couldn't find an appropriate one, and tbh, I'm still just ...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
klo
Got a question about when to concat vs. prepending items to list then reversing to achieve appending. So i know lists boil down to [1 | ...
New

We're in Beta

About us Mission Statement