【译】10个实用的Elixir技巧
Table of Contents
这篇文章质量一般,但是代码多行文少,比较容易看懂,适合我这种英语水平比较挫的来练手。
0.1 原文:10Killer Elixir Tips
1 1. 多个[OR]
# Regular Approach find = fn(x) when x>10 or x<5 or x==7 -> x end # Our Hack hell = fn(x) when true in [x>10,x<5,x==7] -> x end
3 3. 自定义iex配置
将下面的内容保存为=.iex.exs=并放至home目录中,然后打开iex查看奇妙的变化吧
# IEx.configure colors: [enabled: true] # IEx.configure colors: [ eval_result: [ :cyan, :bright ] ] IO.puts IO.ANSI.red_background() <> IO.ANSI.white() <> " ❄❄❄ Good Luck with Elixir ❄❄❄ " <> IO.ANSI.reset Application.put_env(:elixir, :ansi_enabled, true) IEx.configure( colors: [ eval_result: [:green, :bright] , eval_error: [[:red,:bright,"Bug Bug ..!!"]], eval_info: [:yellow, :bright ], ], default_prompt: [ "\e[G", # ANSI CHA, move cursor to column 1 :white, "I", :red, "❤" , # plain string :green, "%prefix",:white,"|", :blue, "%counter", :white, "|", :red, "▶" , # plain string :white, "▶▶" , # plain string # ❤ ❤-»" , # plain string :reset ] |> IO.ANSI.format |> IO.chardata_to_string )
4 4. 自定义Sigils
让名为=x=的sigil调用各自的=sigilx=定义
4.1 自定义Sigils
defmodule MySigils do #returns the downcasing string if option l is given then returns the list of downcase letters def sigil_l(string,[]), do: String.Casing.downcase(string) def sigil_l(string,[?l]), do: String.Casing.downcase(string) |> String.graphemes #returns the upcasing string if option l is given then returns the list of downcase letters def sigil_u(string,[]), do: String.Casing.upcase(string) def sigil_u(string,[?l]), do: String.Casing.upcase(string) |> String.graphemes end
6 6. 从嵌套的Map中取值
=getin=函数可以通过用键组成的列表在嵌套的Map结构中取出对应的值
nested_map = %{ name: %{ first_name: "blackode"} } # Example of Nested Map first_name = get_in(nested_map, [:name, :first_name]) # Retrieving the Key # Returns nil for missing value nil = get_in(nested, [:name, :last_name]) # returns nil when key is not present
参考文档:Kernel.getin/2
7 7. with语句
特殊形式(special form)=with=用于按顺序进行一系列的模式匹配,如果所有子句匹配成功,则返回=do:=中的结果。 但如果其中有子句无法成功匹配,则立即返回未匹配表达式的结果
iex> with 1 <- 1+0, 2 <- 1+1, do: IO.puts "all matched" "all matched" iex> with 1 <- 1+0, 2 <- 3+1, do: IO.puts "all matched" 4 ## since 2 <- 3+1 is not matched so the result of 3+1 is returned.
8 8. 编写Protocol
9 9. 三元操作符
Elixir中并没有类似=true ? "yes" : "no"=这样的三元操作符,不过下面的写法一样可行
"no" = if 1 == 0, do: "yes", else: "no"