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

sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
pgiesin
This should be a simple problem but I just can’t seem to figure it out. I have a standalone Elixir app that won’t find the database. Dep...
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
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
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
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
Codball
Mix format works fine if run from the cmd. I’ve followed this to facilitate the implementation into VSC which involves downloading an ext...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New

Other popular topics Top

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
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
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
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
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
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
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
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
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New

We're in Beta

About us Mission Statement