hack-is-art
hack-is-art

Reputation: 325

Elixir skip operator instead of another message?

I am wondering how I can skip to the end of this function after 3_000 milliseconds but without any other printed message on screen or calling other functions or sending further messages.

defmodule ExampleModule do

    def main do
        Process.send_after(self(), :hello, 2_000)
        send self(), :hello_again
        next()
    end

    def next do
        receive do
            :hello -> IO.puts("Received hello") 
            :hello_again -> IO.puts("Received hello_again")
            after 3_000 -> <SKIP to the very end without recursion>
       end 
        next()
    end
end

Upvotes: 0

Views: 105

Answers (1)

Dogbert
Dogbert

Reputation: 222448

There is no construct like goto or return in Elixir. Here are two ways you can solve this:

  1. Explicitly call next() in the branches you want to continue recursing:

    def next do
      receive do
        :hello ->
          IO.puts("Received hello") 
          next()
        :hello_again ->
          IO.puts("Received hello_again")
          next()
        after 3_000 ->
          :ok
      end 
    end
    
  2. Store the value of the receive expression and call next() based on that:

    def next do
      continue = receive do
        :hello ->
          IO.puts("Received hello") 
          true
        :hello_again ->
          IO.puts("Received hello_again")
          true
        after 3_000 ->
          false
      end 
      if continue, do: next()
    end
    

Upvotes: 2

Related Questions