为什么有一个原子类型(像在酏剂,erlang)吗? [英] Why is useful to have a atom type (like in elixir, erlang)?

查看:146
本文介绍了为什么有一个原子类型(像在酏剂,erlang)吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 http://elixir-lang.org/getting- started / basic-types.html#atoms


原子是他们的名字是自己的值的常量。一些其他
语言调用这些符号


我不知道有什么原子类型。可能帮助构建解析器或宏?但是在日常使用中如何帮助程序员?



BTW:永远不要使用elixir或erlang,只要注意它存在(也在kdb中)


我认为在erlang中最常见的用法之一就是标记变量和消息,并与mipadi说的快速比较(模式匹配)的好处在一起。

解决方案

/ p>

例如,您可以根据提供的参数,连接到服务器的状态或任何原因编写可能失败的功能。一个非常频繁的用法是返回一个元组{ok,Value},如果成功,{error,Reason}如果出现错误。调用函数可以选择只管理成功案例编码 {ok,Value} = yourModule:yourFunction(Param ...)。这样做很明显,您只考虑成功案例,直接从函数返回中提取值,它是快速的,您不必与您的模块共享任何标题来解码ok原子。



在消息中,您经常会看到类似 {add,Key,Value} {delete,Key} {delete_all} {replace,Key,Value} {append,Key,Value} ...这些是明确的消息,具有与前面提到的相同的优点:快速,明智,没有标题的共享...


According to http://elixir-lang.org/getting-started/basic-types.html#atoms:

Atoms are constants where their name is their own value. Some other languages call these symbols

I wonder what is the point of have a atom type. Probably to help build a parser or for macros? But in everyday use how it help the programmer?

BTW: Never use elixir or erlang, just note it exist (also in kdb)

解决方案

I think that one of the most common usage in erlang is to tag variables and messages, with the benefit of fast comparison (pattern match) as mipadi says.

For example you write a function that may fail depending on parameters provided, the status of connection to a server, or any reason. A very frequent usage is to return a tuple {ok,Value} in case of success, {error,Reason} in case of error. The calling function will have the choice to manage only the success case coding {ok,Value} = yourModule:yourFunction(Param...). Doing this it is clear that you consider only the success case, you extract directly the Value from the function return, it is fast, and you don't have to share any header with yourModule to decode the ok atom.

In messages you will often see things like {add,Key,Value}, {delete,Key},{delete_all}, {replace,Key,Value}, {append,Key,Value}... These are explicit messages, with the same advantages as mentioned before: fast,sensible,no share of header...

这篇关于为什么有一个原子类型(像在酏剂,erlang)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆