备注:

文章转自:https://www.djm.org.uk/posts/writing-extensible-elixir-with-behaviours-adapters-pluggable-backends/

This article also offers an intro to the Keyword List type in Elixir; non-beginners can almost certainly skip to the last section.

An intro to Elixir's Keyword Lists

Keyword lists in Elixir are simply a special case of a list, their contents being made up entirely of 2-item "pair" tuples with the first item of each being an Elixir :atom. Unlike maps, they are ordered and may contain multiple values for the same key. Due to their prevalence in the language, a lot of syntactic sugar has been created to make working with them easier and more idiomatic. For example, during creation:

iex(1)> [{:cats, 2}, {:dogs, 1}] == [cats: 2, dogs: 1]
true

You can see that the two ways of defining them are one and the same, the one on the right obviously being the syntactically sugared version.

Passing an optional set of options to a function

Other than creating small k:v stores, this is their primary use case in both Elixir & Erlang. By allowing a client to pass in a keyword list full of options, the function can conditionally change its logic. The keyword list is commonly optional and passed as the last parameter, so common in fact that Elixir has provided more syntactic sugar which allows you to leave off the keyword lists square brackets when it is being passed as the last parameter. For example:

def func_with_options(arg1, opts \\ []) do
# ...
end

..and the function can be called as follows:

# With no options at all..
func_with_options("arg1")
# With options, the non-sugared way.
func_with_options("arg1", [verbose: true, indent: 4])
# With options, with syntactic sugar.
func_with_options("arg1", verbose: true, indent: 4)

Note that in the last instance the function signature is still func_with_options/2; despite the keyword list having 2 elements they are contained inside one list, the arity of the function does not change.

And that leads us on to the main point of this article: what if a function accepts only one parameter and it is a keyword list?

Retrieving the same return for different input

I'm sure there is a much better way of putting that but I do currently know it; this is better showcased by an example. First, let's set the scene:

You have user account functionality in your app and the record for each user contains, amongst others, the fields: usernameemail & ni_number; the user's username, email address, and National Insurance number respectively - all unique, indexed and all strings. You'd like to create some form of a shortcut to retrieve a user record from your data store using any of the aforementioned fields; as they are all unique to the user, only one is required to get a hit.

In quite a few languages, we suffer a problem here as all 3 lookups are string based, we therefore cannot rely on type to allow our helper function to do different things based on the input. If it was just username & email perhaps we could do a check to see if the string contains an '@' sign but that would be a flimsy solution at best, and completely falls apart when we also want to allow lookup by ni_number which like username, is just an alphanumerical string. Thus, a solution to this that I have often seen in various languages is multiple helper methods:

# Pseudo-code
get_user_by_username("harry")
get_user_by_email("harry@example.com")
get_user_by_ni_number("JN032185D") # or even:
User.get_by_username("harry")
User.get_by_email("harry@example.com")
User.get_by_ni_number("JN032185D")

Fine, both ways get the job done but that is about all you can say about them.

In Python, another common pattern is to pass keyword arguments as a form of lookup dictionary:

def get_user(**lookup):
return SomeORM.get(**lookup) get_user(username="harry")
get_user(email="harry@example.com")
get_user(ni_number="JN032185D")

Which is an improvement but in this instance it tightly couples the logic of your wrapper with that of the ORM or underlying data store, as the client must know the field names or the lookup dict might even have a special format (e.g Django's fieldname__iexact lookup filters). This makes the wrapper less useful from an abstraction perspective.

Now, back to Elixir. As we've already said, when the last parameter to a function is a keyword list, you can leave off the square brackets; this also applies when the parameter is also the first and only one. Therefore we can combine multiple function clauses with Elixir's pattern matching to allow:

  • the handling code to split up the differing lookups without using conditional logic. Our brains are not perfect at following conditional branches, following linear code is much less bug-prone.
  • our clients to have a nice API, where they simply hint at the type of lookup they wish for.
defmodule User do

  def get(username: username) do
# Do lookup with username
end def get(email: email) do
# Do lookup with email
end def get(ni_number: ni_number) do
# Do lookup with ni_number
end end # Which gives us a the following API..
User.get(username: "harry")
User.get(email: "harry@example.com")
User.get(ni_number: "JN032185D")

And that is the power that can be achieved by combining multiple function clauses with pattern matching. As with any powerful thing, it will be likely be abused - so only use this pattern in cases where it completely makes sense: if in doubt, multiple parameters to a function is the normal way to go.

This pattern is in fact already in use in the code powering hex.pm; you can see the code base over at the hex_web repository on github.

<wiz_tmp_tag id="wiz-table-range-border" contenteditable="false" style="display: none;">

 
 
 
 

Elixir's keyword lists as option parameters的更多相关文章

  1. EBS initialization parameters - Healthcheck

    APPLIES TO: Oracle EBS Applications Performance - Version 11.5.10.2 to 12.2 [Release 11.5.10 to 12.2 ...

  2. CentOS 7.7安装Erlang和Elixir

    安装之前,先看一下它们的简要说明 Erlang Erlang是一种开源编程语言,用于构建对高可用性有要求的大规模可扩展的软实时系统.它通常用于电信,银行,电子商务,计算机电话和即时消息中.Erlang ...

  3. 关于netty配置的理解serverBootstrap.option和serverBootstrap.childOption

    The parameters that we set using ServerBootStrap.option apply to the ChannelConfig of a newly create ...

  4. PHP Redis 全部操作方法

    Classes and methods Usage Class Redis Class RedisException Predefined constants Class Redis Descript ...

  5. Oracle管理文件OMF (oracle managed files)

    简化dba的管理操作 1:启用 omf 23:16:04 SYS@orcl> show parameter DB_CREATE_FILE_DEST NAME TYPE VALUE ------- ...

  6. Sphinx 2.2.11-release reference manual

    1. Introduction 1.1. About 1.2. Sphinx features 1.3. Where to get Sphinx 1.4. License 1.5. Credits 1 ...

  7. PHP Redis 全部操作方法 转载

    PHP Redis 全部操作方法   Classes and methods Usage Class Redis Class RedisException Predefined constants C ...

  8. acedSSGet 翻译

    ObjectARX 参考指南 > 全局函数 > AcEd 全局函数 > acedSSGet 函数 acedSSGet 折叠全部 C++ int acedSSGet( const AC ...

  9. PHP-redis英文文档

    作为程序员,看英文文档是必备技能,所以尽量还是多看英文版的^^ PhpRedis The phpredis extension provides an API for communicating wi ...

随机推荐

  1. 【程序员笔试面试必会——排序①】Python实现 冒泡排序、选择排序、插入排序、归并排序、快速排序、堆排序、希尔排序

    最近在准备笔试题和面试题,把学到的东西整理出来,一来是给自己留个笔记,二来是帮助大家学习. 题目: 给定一个int数组A及数组的大小n,请返回排序后的数组. 测试样例:  输入:[1,2,3,5,2, ...

  2. SpringMvc+mybatis mybatis在xml文件中大于小于号处理

    方法一:转移字符 用了转义字符把>和<替换掉,然后就没有问题了. SELECT * FROM test WHERE = AND start_date <= CURRENT_DATE ...

  3. Pandas 时间序列数据绘制X轴主要刻度和次要刻度

    先上效果图吧(图中Tue表示周二): Pandas和matplotlib.dates都是使用matplotlib.units来定位刻度. matplotlib.dates可以方便的手动设置刻度,同时p ...

  4. 【hive】lateral view的使用

    当使用UDTF函数的时候,hive只允许对拆分字段进行访问的 例如: select id,explode(arry1) from table; —错误 会报错FAILED: SemanticExcep ...

  5. 从centos6升级到centos7步骤

    1. 备份 2. 安装依赖列表 yum源文件/etc/yum.repos.d/upgrade.repo,内容为 [upgrade] name=upgrade baseurl=http://dev.ce ...

  6. Algorithm1: 全排列

    全排列 思想:      这是一个全排列问题,需要使用递归实现,将数组中的所有元素和第一个元素交换,求后面n-1个元素的全排列.      按照这个条件递归下去,知道元素的个数只有一个的时候,输出所有 ...

  7. c#中事务及回滚

    程序一般在特殊数据的时候,会有数据上的同步,这个时候就用到了事物.闲话不多说,直接上代码. public void UpdateContactTableByDataSet(DataSet ds, st ...

  8. Flask项目中的蓝图简介及使用方式

    Blueprint概念 简单来说,Blueprint 是一个存储操作方法的容器,这些操作在这个Blueprint 被注册到一个应用之后就可以被调用,Flask 可以通过Blueprint来组织URL以 ...

  9. 利用 squid 反向代理提高网站性能(转载)

    本文在介绍 squid 反向代理的工作原理的基础上,指出反向代理技术在提高网站访问速度,增强网站可用性.安全性方面有很好的用途.作者在具体的实验环境下,利用 DNS 轮询和 Squid 反向代理技术, ...

  10. DOM2级事件处理程序

    DOM2级时间定义了两个方法:addEventListener() 和removeEventListener() 他们都接受3个参数:1)要处理的事件名   2)作为事件处理程序的函数 3)一个布尔值 ...