2017-08-30 40 views
0

我是Elixir的新手。我正在嘗試在模塊中運行一個函數。我在文件中的代碼如下:變量在訪問elixir中的模塊中的函數時不存在編譯錯誤

warning: variable "greeter" does not exist and is being expanded to "greeter()", please use parentheses to remove the ambiguity or change the variable name 
functions.ex:1 
== Compilation error in file functions.ex == 
** (CompileError) functions.ex:1: undefined function greeter/0 
    (stdlib) lists.erl:1354: :lists.mapfoldl/3 
    (elixir) expanding macro: Kernel.defmodule/2 
    functions.ex:1: (file) 

我無力解決給定的錯誤:

defmodule greeter do 

    def print() do 
    IO.puts "Hello workd" 
    end 

    def print(name) do 
    IO.puts "Hello " <> name 
    end 

    defp print(name,age) do 
    IO.puts "Hello " <>name<>" My age is "<> age 
    end 

end 

greeter.print() 
greeter.print("Xyxss") 

當我在我的命令行我碰到下面的錯誤運行elixirc filename.ex。有人可以幫助我嗎?

回答

1

我會在這裏放一個正確的答案,因爲答案提供@ J.Sebio顯然是錯誤的。

Elixir中的模塊名稱必須是原子。下面完美的工作這兩個例子:

iex(1)> defmodule :foo, do: def yo, do: IO.puts "YO" 
iex(2)> :foo.yo 
YO 

iex(3)> defmodule :"42", do: def yo, do: IO.puts "YO" 
iex(4)> :"42".yo          
YO 

的事情是:在花好月圓,資本項是原子

iex(5)> is_atom(Greeting) 
true 

這就是爲什麼資本化模塊的名稱的工作。另外,greeting是一個普通變量,這就是編譯器試圖在現場解決它並引發錯誤的原因。

+0

我不知道我會說他的答案是「明顯錯誤的」 - 更多的問題與他誤解最初的大寫字母在代碼中做了什麼。他有點正確,但是出於錯誤的原因。 –

+0

@OnorioCatenacci我承認我誇大了措辭,但是「在萬靈藥中,模塊被寫成大寫」是一種騙局。這裏最主要的是要首先了解根本原因,而不是寫一切以大寫字母開頭的東西。而從erlang導出的btw模塊仍然是lowercased':observer.start'。 – mudasobwa

0

在仙丹的模塊是大寫的,和正常寫入CamelCase,所以,你的情況,你有你的代碼改寫爲:

defmodule Greeter do 

    def print() do 
     IO.puts "Hello workd" 
    end 

    def print(name) do 
     IO.puts "Hello " <> name 
    end 

    defp print(name,age) do 
     IO.puts "Hello " <>name<>" My age is "<> age 
    end 

end 

Greeter.print() 
Greeter.print("Xyxss") 
+0

我不知道。我把這個函數改成了CamelCase,它工作。謝謝。如果你可以在提到的仙丹文檔中找到鏈接,那將是非常棒的。 – shubhamagiwal92

+0

@ shubhamagiwal92不客氣。我認爲你不能以明確的方式找到它,但[這裏](https://elixir-lang.org/crash-course.html#modules),你可以閱讀'defmodule HelloModule',你可以想象模塊是資本化。 –

+0

這是錯誤的,請參閱我的答案以獲得正確的解釋。 – mudasobwa