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

beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> somethi...
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
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
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
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: The documentation above suggests that while ...
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
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
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
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
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
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
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
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
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
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
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

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement