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
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)
2
Also Liked
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")
])
5
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)
3
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()
2
Popular in Questions
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
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
can someone please explain to me how Enum.reduce works with maps
New
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible.
total = 10
while total != 0
...
New
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
I am trying to implement my new.html.eex file to create new posts on my website.
new.html.eex:
<h1>Create Post</h1>
<...
New
I will often find my self writing things similar to:
case some_value do
nil -> something()
"" -> something()
_ -> someth...
New
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set?
Thanks.
New
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
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
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
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
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
Phoenix 1.4.0 released
Phoenix 1.4 is out! This release ships with exciting new features, most notably
with HTTP2 support, improved deve...
New
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
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
New
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
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
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
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








