anthonyl

anthonyl

Pipe to Complex Map

I need to do the following:

  1. Read data from file
  2. Parse custom syntax
  3. Write result to a map

I have the following code:

File.stream!(load_path,[:read, :utf8]) #Read File
    |> Stream.map(&String.trim(&1)) #Trim Each Element
    |> Stream.map(&String.downcase(&1)) #Convert to Lowercase
    |> Stream.map(&String.split(&1, [":", ","])) #Split at Delimiters
    |> Stream.map(&Map.put(%{}, create_index_name(hd(&1)), tl(&1))) #Write to Map
    |> Enum.map(&IO.inspect(&1)) #Enumerate through stream

Which outputs a list with map entries in it like so:

[
  %{":jhb_team_names" => ["hawks", "maulers", "eagles", wolves"]},
  %{":dbn_team_names" => ["sqeaks", "bunfighters"]}
]

I need it to output something like:

  %{":jhb_team_names" => ["hawks", "maulers", "eagles", wolves"],
  	:dbn_team_names" => ["sqeaks", "bunfighters"]}

i.e. a single map, which can be simply accessed with a key => value lookup.

This should be simple to do, but my newness to Elixir is stumping me.

Any suggestions on how this can be accomplished?

Marked As Solved

dimitarvp

dimitarvp

You’ll have to modify part of the code to read the data from a file but otherwise it works. Key insight: use Enum.reduce to accumulate values into a single return value, instead of making a one-keyed map for each parsed line.

defmodule Parse1 do
  def data(), do: ~S"""
  jhb team names:hawks,maulers,eagles,wolves
  dbn team names:sqeaks,bunfighters
  """

  def stream_string(text) do
    {:ok, io} = StringIO.open(text)
    IO.stream(io, :line)
  end

  def create_index_name(name) do
    ":" <> String.replace(name, " ", "_")
  end

  def test() do
    # Replace first two lines with your file reading code.
    data()
    |> stream_string()
    |> Stream.map(&String.trim(&1))
    |> Stream.map(&String.downcase(&1))
    |> Stream.map(&String.split(&1, [":", ","]))
    |> Enum.reduce(%{}, fn [head | tail], acc ->
      Map.put(acc, create_index_name(head), tail)
    end)
  end
end

Copy-paste that in iex and then run Parse1.test().

Also Liked

dimitarvp

dimitarvp

Can you post some example source data (and possibly the source of create_index_name)? Also, please format your code blocks with triple backticks, right now it’s almost unreadable.

anthonyl

anthonyl

Thx, it works perfectly now!

Also thx for the education to improve my knowledge :grinning:.

gregvaughn

gregvaughn

In this case, I wouldn’t even bother with the Stream.map calls. The extra indirection is slowing you down and adding complexity for no real benefit. Thanks to @dimitarvp 's nice sample code, I took it and modified a bit to be more direct.

defmodule Parse2 do
  def data(), do: ~S"""
  jhb team names:hawks,maulers,eagles,wolves
  dbn team names:sqeaks,bunfighters
  """

  def stream_string(text) do
    {:ok, io} = StringIO.open(text)
    IO.stream(io, :line)
  end

  def create_index_name(name) do
    ":" <> String.replace(name, " ", "_")
  end

  def line_to_kv(line) do
    [key | names] =
      line
      |> String.trim()
      |> String.downcase()
      |> String.split([":", ","])

    {create_index_name(key), names}
  end

  def test2() do
    # Replace first two lines with your file reading code.
    data()
    |> stream_string()
    |> Map.new(&line_to_kv/1)
  end
end

Where Next?

Popular in Questions Top

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
Tee
can someone please explain to me how Enum.reduce works with maps
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
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
nobody
How to bind a phoenix app to a specific ip address? could not find anything about that, nowhere, unfortunately, but for me this is quite...
New
jaysoifer
Is there a way to rollback a specific migration and only that one (“skipping” all the other ones)? Would mix ecto.rollback -v 200809061...
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
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
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 records...
New
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

Other popular topics Top

lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
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
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
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
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
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
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

We're in Beta

About us Mission Statement