sztosz

sztosz

Programming Elixir - A Fibonacci Server

Hi, somehow, after typing code from book i managed only to make my code stuck at infinite loop. I did comparision side by side of my code to that i get from zipped examples i got with book (code from zip works ok). I can’t find where did i do mistake. Can anyone spot what did do wrong? I know i can move on, i understand what is going on, but it’s driving me nuts, beside, there is a big chance i won’t repeat that mistake if only i would know where it is :frowning:

Anyway, here’s the code:

defmodule FibSolver do

  def fib(scheduler) do
    send(scheduler, { :read, self })
    receive do
      { :fib, n, client } ->
        send(client, { :answer, n, fib_calc(n), self })
        fib(scheduler)
      { :shutdown } ->
        exit(:normal)
    end
  end

  defp fib_calc(0), do: 0
  defp fib_calc(1), do: 1
  defp fib_calc(n), do: fib_calc(n-1) + fib_calc(n-2)
end

defmodule Scheduler do
  
  def run(num_processes, module, func, to_calculate) do
    (1..num_processes)
    |> Enum.map(fn(_) -> spawn(module, func, [self]) end)
    |> schedule_processes(to_calculate, [])
  end

  defp schedule_processes(processes, queue, results) do
    receive do
      { :ready, pid } when length(queue) > 0 ->
        [ next | tail ] = queue
        send(pid, { :fib, next, self })
        schedule_processes(processes, tail, results)
      { :ready, pid } ->
        send(pid, { :shutdown })
        if length(processes) > 1 do
          schedule_processes(List.delete(processes, pid), queue, results)
        else
          Enum.sort(results, fn {n1,_}, {n2,_} -> n1 <= n2 end)
        end
      { :answer, number, result, _pid } ->
        schedule_processes(processes, queue, [{ number, result } | results])
    end
  end
end

to_process = [37, 37, 37, 37, 37, 37]

Enum.each(1..10, fn num_processes ->
  { time, result } = :timer.tc(Scheduler, :run, [num_processes, FibSolver, :fib, to_process])
  if num_processes == 1 do
    IO.puts(inspect(result))
    IO.puts("\n #  time(s)")
  end
  :io.format("~2B     ~.2f~n", [num_processes, time/1000000.0])
  end)

Most Liked

lionize

lionize

Looks like that should be {:ready, self}. Can’t start the circus if it’s never telling the Scheduler it’s ready. :slight_smile:

sztosz

sztosz

Thank you very much. Such typos are hard to spot, i normally rely on IDE to help me with them, but i have none for elixir :slight_smile:

I think the lesson for me is to also pattern match “anything” at end of receive and exit program printing the oddity I just catch, at least when I’m learning :wink:

PS. Func fact: Single core performance of my 1.6 Ghz i5 in mac book air (OSX) is better than single core performance of 3.7 Ghz AMD (Win10)

rvirding

rvirding

Creator of Erlang

Deciding what to do when you get a message in which you are not interested is a general problem. Should I crash, or should I ignore it, or what? Unfortunately there is no general solution which is good for everyone everywhere.

Just some philosophy.

Robert

Where Next?

Popular in Questions 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
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
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
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: The documentation above suggests that while ...
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
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
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
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" =&gt; #BSON.ObjectId&lt;58eb1a7a9ad169198c3dXXXX&gt;, "email" =&gt; ...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

Other popular topics Top

Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
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
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
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 31013 112
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
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
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 52673 488
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

We're in Beta

About us Mission Statement