Return statement in Elixir

后端 未结 8 1412
野趣味
野趣味 2020-12-14 00:38

I need a function with some kind of a step-by-step logic and I wonder how I can make one. Let\'s take a log in process on a site as an example, so I need the following logic

8条回答
  •  [愿得一人]
    2020-12-14 01:16

    I missed return so much that I wrote a hex package called return.

    The repository is hosted at https://github.com/Aetherus/return.

    Here is the source code for v0.0.1:

    defmodule Return do
      defmacro func(signature, do: block) do
        quote do
          def unquote(signature) do
            try do
              unquote(block)
            catch
              {:return, value} -> value
            end
          end
        end
      end
    
      defmacro funcp(signature, do: block) do
        quote do
          defp unquote(signature) do
            try do
              unquote(block)
            catch
              {:return, value} -> value
            end
          end
        end
      end
    
      defmacro return(expr) do
        quote do
          throw {:return, unquote(expr)}
        end
      end
    
    end
    

    The macros can be used like

    defmodule MyModule do
      require Return
      import  Return
    
      # public function
      func x(p1, p2) do
        if p1 == p2, do: return 0
        # heavy logic here ...
      end
    
      # private function
      funcp a(b, c) do
        # you can use return here too
      end
    end
    

    Guards are also supported.

提交回复
热议问题