rabet

rabet

Learning / proper use of cond (and other Elixir style)

Hey all dear Elixir fans and pros,

I try to learn with wiritng the most-elixirish functional code, sometime with the help of you.

I am just writing a parsing module, which extracts some info from recieved JSON (different shapes), and come up with this functions:

def get_markets do
    for {market, url} <- get_markets_urls() do # get_markets_urls just query my db for market name and it's url (about 5-10 records max.)
      case get(url) do
        {:ok, val} -> parse_markets(val.body, market)
        {:error, reason} -> IO.puts "Error: #{reason}"
      end
    end
  end

  defp parse_markets(response, market) do
    IO.puts "Parsing markets"
    cond do
      market == "Market1" ->
        IO.puts Enum.map(response, &(Map.get(&1, "asset")))
      market == "Market2" ->
        Enum.map(Map.get(response, "data"), &(marketClient(&1, market)))
      market == "Market3" ->
        IO.puts Enum.map(response, &(&1))
      true -> "Other"
    end
  end

As you can see, for every market I need to extract different info (because of different response shape).
Please, is this a good way to write it? Coud it be written by better, more functional way?

Thanks for the hints!

R.

Most Liked

kokolegorille

kokolegorille

Maybe You can improve with multiple functions… like this

defp parse_markets(response, "Market1"), do: #whatever
defp parse_markets(response, "Market2"), do: #whatever
defp parse_markets(response, "Market3"), do: #whatever
defp parse_markets(response, _), do: #whatever
peerreynders

peerreynders

Also while there is nothing wrong with comprehensions it seems that your are holding on too tightly to iteration.

If you are going through the list for side effects I’d expect to see Enum.each/2 instead or if you wanted conditional transformation I’d expect some piped combination of Enum.filter/2 and Enum.map/2 (though comprehensions can have filters as well).

At the very least I’d make the comprehension look less like a loop, e.g.

def get_markets, 
  do: for {name, url} <- get_market_urls()
          do: get_market_data(name, url)

vs

def get_markets,
  do: Enum.map(get_market_urls(), fn {name,url} -> get_market_data(name,url) end)

or

def get_market_data({name,url}) do: 
  ...
end

def get_markets,
  do: Enum.map(get_market_urls(), &get_market_data/1)

(In general I’d dial back on the use of inline anonymous functions that is so common in JavaScript)

NobbZ

NobbZ

As all your branches do compare for equality of market against a string literal a case were much more idiomatic.

Also I’m not quite sure why in the parse_markets/2 you are returning :ok (an atom) most of the time but "Other" (a string) on unknown markets.

iboard

iboard

A “Clean Coder” advice: I would prefer the pattern-match solution by @kokolegorille for one reason: You can add new “Markets” without changing the existing code but by just adding a new function-header for “Market4”.

Where Next?

Popular in Questions Top

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
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
sacepums
Hey guys. I'm new to elixir and im really stocked about it. But I ran into a bit of problem - I need to convert a date sting, for examp...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
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
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

Other popular topics Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
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
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
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
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
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New

We're in Beta

About us Mission Statement