quda

quda

Help for a simple queue wrapper

I need to implement a (simple) queue wrapper on the Erlan :queue, as Elixir does not have something similar :frowning_face: and this Erlang implementation of queue is not handy to use.
I warn that I have little experience with Elixir and fp in general, I am coming from the OOP world - classes, objects, this, self, closure etc.
I wrote this:

defmodule Fifo do
  def new do
    :queue.new()
  end

  def in!(x, q) do
   :queue.in(x, q)
  end

  def out!(q) do
    :queue.out(q)
  end
end

Result => disaster!

q = Fifo.new
{, } # As expected

Then:

Fifo.in!(3, q)
{[3], } # As expected as well

Then came the unexpected:

iex(26)> Fifo.in!(2, q)
{[2], } # Whoops! I expected {[2,3]}
iex(27)> Fifo.in!(“r”, q)
{[“r”], } # expected {[“r”,2,3]}

The disaster completes:

iex(28)> q
{, } #:sob::sob::sob: My queue q is empty!!

There’s clearly something wrong with my implementation, I needed some sort of closure; “this” does not exist in Elixir; the state is not recorded, my variable q is lost on the way.
Please… how to do this ? Help!

Marked As Solved

dorgan

dorgan

No, you can’t avoid rebinding, there’s no implicit mutable state, there are no stateful objects in functional land. Modules are not like classes, they’re just a bag of functions. Everything you do in the language will behave like that. This requires you to approach problems with a different mindset and you should not try to force OOP patterns here.

If you want to keep the state and “mutate” it over time, then you can spawn a genserver and keep the queue as it’s state. Check the elixir guide to see an example of a stateful Key-Value store.

q = Fifo.new() |> Fifo.in!(1)

# do something else

q = Fifo.in!(q, 2)

There’s no other way around it, the whole language works this way, it has nothing to do with the way the queue is implemented in erlang(it’s just a data structure).

Also Liked

dorgan

dorgan

The code in your module is ok, but in Elixir data is immutable, each time you add or remove an item from the queue, a new queue is returned, so you have to rebind q to the result of Fifo.*

iex(2)> q = Fifo.new
{[], []}
iex(3)> q
{[], []}
iex(4)> q = Fifo.in!(2, q)
{[2], []}
iex(5)> q
{[2], []}
iex(6)> Fifo.in!("r", q)
{["r"], [2]}
iex(7)> q = Fifo.new
{[], []}
iex(8)> q = Fifo.in!(3, q)
{[3], []}
iex(9)> q = Fifo.in!(2, q)
{[2], [3]}
iex(10)> q = Fifo.in!("r", q)
{["r", 2], [3]}
iex(11)> q
{["r", 2], [3]}

Also bear in mind that erlang usually has the data in the last argument(common in many other functional languages, it is useful when using currying and partial function application), but in elixir it’s more common to have the data(in this case the queue) in the first argument, so you can leverage the pipe |> operator:

defmodule Fifo do
  def new do
    :queue.new()
  end

  def in!(q, x) do
   :queue.in(x, q)
  end

  def out!(q) do
    :queue.out(q)
  end
end

q =
  Fifo.new()
  |> Fifo.in!(3)
  |> Fifo.in!(2)
  |> Fifo.in!("r")
#=> {["r", 2], [3]}

Where Next?

Popular in Questions Top

Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
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
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
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
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
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
Lily
In templates/appointment/index.html.eex: <%= for appointment <- @appointments do %> <tr> <td><%= appoi...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => ...
New

Other popular topics Top

chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
AstonJ
Please see the new poll here: Which code editor or IDE do you use? (Poll) (2022 Edition) It’s been a while since we first asked this, I...
208 31142 143
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
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
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => ...
New

We're in Beta

About us Mission Statement