Back

elixir - 常见的语法汇总 - 奇怪的语法

发布时间: 2022-01-27 00:36:00

打印某个变量

IO.puts inspect(var) 

|<  管道操作符 , 默认传入第一个参数

result = a
  |<  func1
  |<  func2

等同于:
temp1 = func1 a  
result = func2 temp1

后者的代码更加容易调试一些

%{}   定义一个hash,  

%{ a: 'ei', b: 'bi' }

alias A.B  

这里看起来是缺少了第二个参数,实际上等同于    alias A.B B,   在后面的代码中可以直接调用B

def some_method when xx do

fn -> .. end;    a.()  

这是调用一个匿名函数的声明和调用。  ( 参考: https://elixirforum.com/t/syntax-question-and/1415)

<-    用来做匹配的

参考:https://til.hashrocket.com/posts/6a6f5e9fff-elixir-with-macro-and-

下面是  <- 与 = 的比较

正常运行时:
with {:ok, width} <- Map.fetch(%{width: 10}, :width),
  do: {:ok, 2 * width}
#=> {:ok, 20}

with {:ok, width} = Map.fetch(%{width: 10}, :width),
  do: {:ok, 2 * width}
#=> {:ok, 20}

报错时:
with {:ok, width} <- Map.fetch(%{height: 10}, :width),
  do: {:ok, 2 * width}
#=> :error

with {:ok, width} = Map.fetch(%{height: 10}, :width),
  do: {:ok, 2 * width}
#=> ** (MatchError) no match of right hand side value: :error

Tuple

这个对于python超级常见,但是对于java/ruby的人理解不能。emscript里面也有。

{1,2,3}  是一个容器,不需要迭代。

类似于ruby/java的struct .   可以把它定义成一个class

class A
   attr_accessor:  :a, :b, :c
end
temp = A.new
temp.a = 1
temp.b = 2
temp.c = 3

elixir中会大量用到,因为会有  {:ok, result } = SomeClass.calculate() .. 这样的函数

在match中也会用到(见with )  

with

参考:https://www.openmymind.net/Elixirs-With-Statement/

类似于before filter

with

Back