elixir 笔记 _____ 学习 随笔记

1) 给params的list转小写  匿名函数 

例: params = [“A”,“B”,“C”]

       Enum.map(params, fn (x) -> String.downcase(x) end )

或者 Enum.map(parmas, fn x -> String.downcase(x) end)

输出为:["a","b","c"]

 

  

2)Enum.map

iex下输入:

Enum.map(%{"a"=>"1" , "b"=>"2" },fn {k,v} -> k <> v end )
["a1", "b2"]

  

输入:

iex(1)>Enum.map([1,2,3],fn x -> x*2 end )
[2, 4, 6]
iex(2)> Enum.map(%{1=>2 , 3=>4 },fn {k,v} -> k * v end )
[2, 12]

  

 

遍历列表:

  def sum([]) do
     0
  end
  def sum([head|tail]) do
       head + sum(tail)
  end

iex(1)> MyProject.sum([1,2,3])
6

例子2:

 

  def double_each([head | tail]) do
    [head * 2 | double_each(tail)]
  end

  def double_each([]) do
    []
  end

 

输出:  

iex(2)> MyProject.double_each([1,2,3])
[2, 4, 6]

 

Enum.map_jon()

iex(1)> list = [1,2,3]
iex(2)> list |> Enum.map_join("=", fn x ->  Integer.to_string(x) end)
"1=2=3"
iex(3)> list |> Enum.map_join(fn x -> "=" <>  Integer.to_string(x) end)
"=1=2=3"
iex> Enum.map_join([1, 2, 3], &(&1 * 2))
"246"

iex> Enum.map_join([1, 2, 3], " = ", &(&1 * 2))
"2 = 4 = 6"

 

reduce 操作:

Enum.reduce   <=> List.foldl

Enum.reduce([1,2,3,4], 0, fn (x,acc) ->x - acc end)

or 

Enum.reduce([1,2,3,4], 0, fn (x,acc) ->x - acc end)



List.foldl([1,2,3,4], 0 , fn(x, acc) -> x - acc end )

 

into(enumerable, collectable)

iex> Enum.into([1, 2], [0])
[0, 1, 2]

iex> Enum.into([a: 1, b: 2], %{})
%{a: 1, b: 2}

iex> Enum.into(%{a: 1}, %{b: 2})
%{a: 1, b: 2}

iex> Enum.into([a: 1, a: 2], %{})
%{a: 2}

 


关于Agent的操作:

iex(1)> {:ok,pid} = Agent.start_link(fn ->2 end)
{:ok, #PID<0.351.0>}

iex(2)> Agent.cast(pid, fn state -> state + 2 end)

iex(3)> Agent.get(pid,fn state -> state end)
4
iex(4)> Agent.cast(pid, fn state -> state + 3 end)
:ok
iex(5)> Agent.get(pid,fn state -> state end)
7

  

 

posted @ 2022-06-08 14:17  孤独信徒  阅读(15)  评论(0编辑  收藏  举报