Elixir 之 Module,Function,Imports,aliases,comments

Elixir 之 Module,Function,Imports,aliases,comments

1.Module模块

        defmodule ModuleName do
			...
		end
ModuleName 指模块名, 以大写字母开始,通常采用驼峰命名法,可包含字母、数字、下划线、顿号(.),在这里顿号没有其它意义。字母通常用来组织模块层级,例如
     defmodule Geometry.Rectangle do
	 	...
	 end
	 defmodule Geometry.Circle do
	 	...
	 end
	在一个.ex文件中可以包含多个模块, 但一个模块必须在一个文件中
	可以用  iex xxx.ex对单个文件编译,然后测试该文件里边的功能模块
	也可以在模块中定义子模块,例如
       defmodule Geometry do
			defmodule Rectangle do
			end
			defmodule Cricle do
			end
		end
	但Geometry 和 Geometry.Rectangle没有特别关系
  1. Function 函数
    函数名以小写字母或下划线(_)开始,由字母、数字、下划线组成
    函数名像变量一样,能够以? 和!结尾, ?表示这个函数的返回值是true或false, !表示这个函数可能会发生运行时错误
    每个函数都有返回值,函数的最后一个表达式的结果作为返回值
    如果一个函数定义很短,可以缩小到一行,例如
    defmodule Geometry do
		def  rectangle_area(a,b), do: a*b
		defp  square_area(a), do: a*a 
	end
def表示这个函数是public的, defp表示这个函数是private,即只能在模块内部访问
注:鉴于elixir是函数语言,通常需要关联函数,用一个函数的返回值作为另一个函数的参数,elixir拿出一个内置操作符|>,叫做管道(pipeline)操作符
例如在shell中输入 -5 |> abs |> Integer.to_string |> IO.puts
执行结果5
等价于IO.puts(Integer.to_string(abs(-5)))
管道操作符执行顺序,从左到右
通常,管道操作符 用上一个调用的结果  作为下一个调用的第一个参数
注: 在shell中用多行管道操作符会报错,但在文件中没事(原因:Multiline pipelines don't work in the shell. The previous code is an example of a syntax that works only in the source file and can’t be entered

directly in the shell. When you paste this code into the shell, it will raise an error. The reason is that the first line is a proper standalone Elixir expression, and the shell will execute it immediately. The rest of the code isn’t syntactically correct, because it starts with the |> operator.)
3. Function arity 函数参数
exlixir允许一个函数名一样的函数有多个不同的参数,即函数重载,同时支持默认参数,通过操作符\,放到需要默认值的参数后边,例如

defmodule Test do
     		def  test1(a),  do: a 
     		def  test1(a,b) do
     			a+b
     		end
     		def sum(a, b \\ 0) do #这里两个斜线之间没有空格
     				a+b
     		end
 	end

4.Import和Aliases
Import一个模块,调用这个模块的def函数时, 不用通过模块名.functionname方式, 直接写functionname(参数)就行
Aliases 起别名, 如果一个模块的名字比较长如:AAA.BBB.CCC,可以通过aliases AAA.BBB.CCC, as: ABC, 之后就可以通过ABC.funname访问模块的函数了
5.模块属性, 用@pi属性定义一个常量,
@spec属性预示area这个函数接收一个number参数和返回一个number类型

defmodule Circle do
		@pi 3.14159
		  @spec area(number) ::number
		  def area(r), do: r*r*@pi
	end
6、注释
elixir中注释用#开始,不支持块注释
defmodule Circle do
	#this is a comment
end
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值