Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to comment out line(s) of code in function in Elixir

Tags:

elixir

Is there any ways to comment out a line or lines of code in a function?

something like the following

defmodule MyModule
  def foo do
    //a = "old code"
    a = "new code"
  end
end

or

defmodule MyModule
  def foo do
    /*a = "old code"
    b = 1234 */
    a = "new code"
  end
end
like image 677
Letseatlunch Avatar asked Jul 29 '15 04:07

Letseatlunch


2 Answers

Comments in Elixir, as is common in languages that can function as scripting languages, use the pound sign.

defmodule MyModule
  def foo do
    # a = "old code"
    a = "new code"
  end
end

Formally, there's no way to have a multiline comment, but a multiline string will end up being a noop.

defmodule MyModule
  def foo do
    """
    a = "old code"
    a = "more old code"
    """
    a = "new code"
  end
end
like image 149
Silvio Mayolo Avatar answered Oct 12 '22 20:10

Silvio Mayolo


I'm far from an expert, but I don't think this answer works in all cases. If the multi-line string is at the end of a function it will be returned as the function's result. So I think the following reordering of the answer's code fails (or at least doesn't operate as expected). It returns "a = \"old code\"\na = \"more old code\"\n". Also note that there is a missing do in the answer on the defmodule line. Finally, code using """ for multiple comments will generate an unused literal error (whereas ''' will not).

defmodule MyModule do
  def foo do
    a = "new code"
    """
    a = "old code"
    a = "more old code"
    """
  end
end

So, if the multi-line comment technique doesn't work (in all cases), how should we block out a section of code?

You can't set an attribute (e.g. @comment """... inside a function) so that won't work.

You could use macros as in this question but that "pollutes" the code a bit.

I've Googled around a bit and can not find a suitable answer (maybe I'm missing something obvious) so I'll just hack up some elisp code to block out a section in Emacs by prepending each line with # (if it's not already in the Elixir mode package).

like image 20
Los Alamos Al Avatar answered Oct 12 '22 21:10

Los Alamos Al