jazzyer

jazzyer

Iterating or Pattern Matching on a certain conditions

I have a pretty straight-forward problem, but struggle to make it clear and concise (is that possible at all!?).

So having two lists:

list_1 = ["$100", "$200", "$300"]
list_2 = ["bob", "$200", "sam"]

success output should be:

"bob: $100, sam: $300"

fail output:

list_1 = ["$100", "$200", "$300"]
list_2 = ["bob", "bob", "sam"]
false

Obviously, list_2 (or our pattern) might be different, but if prices are matching we should return a success output similar to above.

I approached it right away by:

iex(2)> Enum.zip(["bob", "$200", "sam"], ["$100", "$200", "$300"])
[{"bob", "$100"}, {"$200", "$200"}, {"sam", "$300"}]

and then with a lot of conditional logic and accumulators in Enum.reduce solved the problem, but it’s super ugly… When my Elixir code is ugly - I’m always questioning myself, since there is always another and cleaner way.

How would you approach this? Is there a way?

Thank you all in advance!

Marked As Solved

gregvaughn

gregvaughn

Format more nicely in production code, but here’s a quick iex solution

iex(91)> list_1 = ["$100", "$200", "$300"]
["$100", "$200", "$300"]
iex(92)> list_2 = ["$100",  "tom", "sam"]
["$100", "tom", "sam"]
iex(93)> pairs = Enum.zip(list_1, list_2)
[{"$100", "$100"}, {"$200", "tom"}, {"$300", "sam"}]
iex(94)> if Enum.any?(pairs, &match?({a, a}, &1)), do: Enum.join((for {a, b} <- pairs, a != b, do: "#{b}: #{a}"), ", "), else: false
"tom: $200, sam: $300"

Also Liked

al2o3cr

al2o3cr

Based solely on what you’ve posted (I don’t really understand why list_2 has a mix of names and amounts):

list_1 = ["$100", "$200", "$300"]
list_2 = ["bob", "$200", "sam"]

pairs = Enum.zip(list_1, list_2)

unmatched_pairs = Enum.reject(pairs, fn {l1, l2} -> l1 == l2 end)

if length(unmatched_pairs) == length(list_1) do
  false
else
  unmatched_pairs
  |> Enum.map(fn {l1, l2} -> "#{l1}: #{l2}" end)
  |> Enum.join(", ")
end

(Edited to fix a bug - was looking at length(pairs) without filtering first)

al2o3cr

al2o3cr

Nope, you’re not missing anything - that was a bug! :slight_smile:

The intent is to check the length of the zipped pairs after filtering out ones like {"$200", "$200"} - if none of the pairs got filtered out, we need to return false (a “fail case”).

czrpb

czrpb

i too dont think i understand the 2 lists, but here is what i have for your 3 tests/examples:

iex(5)> test1 = {["$100", "$200", "$300"], ["bob",  "$200", "sam"]}
{["$100", "$200", "$300"], ["bob", "$200", "sam"]}
iex(6)> test2 = {["$100", "$200", "$300"], ["$100",  "tom", "sam"]}
{["$100", "$200", "$300"], ["$100", "tom", "sam"]}
iex(7)> test3 = {["$100", "$200", "$300"],["bob",  "tom", "sam"]}
{["$100", "$200", "$300"], ["bob", "tom", "sam"]}
iex(8)> [test1, test2, test3] |>
...(8)> Enum.map(fn {list1, list2} ->
...(8)>   Enum.zip(list1, list2) |>
...(8)>   Enum.reduce({false, []}, fn
...(8)>     {l1,l1}, {_, pairs} -> {true, pairs}
...(8)>     l1l2, {result, pairs} -> {result, [l1l2|pairs]}
...(8)>   end)
...(8)> end)
[
  true: [{"$300", "sam"}, {"$100", "bob"}],
  true: [{"$300", "sam"}, {"$200", "tom"}],
  false: [{"$300", "sam"}, {"$200", "tom"}, {"$100", "bob"}]
]

result/accumulator of the reduce is a tuple: {PASS-FAIL, PAIRS}

jazzyer

jazzyer

@czrpb and @gregvaughn
Thank you so much for your input and sorry about my delay here! That pandemic definitely is not over, got sick finally :frowning:

Again, really appreciate it!

Where Next?

Popular in Questions Top

openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
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
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New

Other popular topics 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
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
sergio
I couldn’t find any guides that worked well with Phoenix 1.6.0 and esbuild. I hope this helps people test the waters and eases you into t...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 35421 110
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New

We're in Beta

About us Mission Statement