Erlang快速入门(二)

Erlang快速入门开始编码之后,慢慢就会接触到编译错误的情况了。

编译时关键字冲突之类,变量名和默认函数重名等

 

比如 “init terminating in do_boot” 什么的,像这种编译错误,可以先查看一下是不是有关变量和 Erlang 关键字冲突了。

after and andalso band
begin bnot bor bsl
bsr bxor case catch
cond div end fun
if let not of
or orelse receive rem
try when xor

有一次我使用 abs 求绝对值函数的时候,就错误的把一个变量设置为 Abs 结果就报错了。

Erlang 输出类型错误

 

而且可能你类型写不对,他也报错。比如

% 这样写

 

Fnum = float(4),
fwrite(“Fnum is float?: ~f\n”,[is_float(Fnum)]),

% 会报错

{“init terminating in do_boot”,{badarg,[{io,fwrite,[“Fnum is float?: ~f\n”,[true]],[{file,”io.erl”},{line,99},{error_info,#{cause=>{device,put_chars},module=>erl_stdlib_errors}}]},{list_learn,start,0,[{file,”list_learn.erl”},{line,37}]},{init,start_em,1,[]},{init,do_boot,3,[]}]}}
init terminating in do_boot ({badarg,[{io,fwrite,[[_],[_]],[{_},{_},{_}]},{list_learn,start,0,[{_},{_}]},{init,start_em,1,[]},{init,do_boot,3,[]}]})

Crash dump is being written to: erl_crash.dump…done

 

换成

 Fnum = float(4),

fwrite(“Fnum is float?: ~w\n”,[is_float(Fnum)]),

这样就没啥问题。

 

参数错误

 

io:fwrite 函数输出时里面有一个中括号的,手敲忘记这个中括号,很可能会这样报错。

{“init terminating in do_boot”,{badarg,[{io,fwrite,

% fwrite(“list append result:~w\n”,ListSever). 这一行导致的

正确写法

fwrite(“list append result:~w\n”,[ListSever]).

而且 中括号这个位置,最好不要直接用列表的 append 等函数。不然运行时也会报错。

变量首字母

变量开头首字母必须大写,不然编译通过了。运行也会报错。

 

Erlang 索引

Erlang 的索引是从1开始的!这点要熟记于心,尤其是多语言作战的程序员们,写着写着这个容易混淆。

 

Erlang 退出远程 Shell 要小心

【使用完远程shell打算退出时,你的手指可能不自觉地就敲出了q(). ,停!千万别回车!这个命令是init:stop() 的简写,用于关闭执行该命令的节点:也就是你的远程节点。恐怕每个Erlang程序员都曾经被这块石头绊过。要想安全退出,请使用Ctrl-G和Ctrl-C(或Ctrl-Break),这两个组合键只对本地节点有效。键入Ctrl-G加Q,或Ctrl-C(在Windows上是Ctrl-Break)加A,都可以在不影响远程节点的情况下关闭本地节点。】g

 

迷之Erlang 的类型

 

你说他有类型吧,一个 list 列表里面既可以放数字,也可以放字符串。你说他没类型的吧,他的类型又分 Number, Atom, Boolean, Bit String, Tuple, Map, List 。完全不能用 C like 的思维去看 Erlang 。

 

元组的首字母是要用小写的开头的。

-module(tuple_learn).
-import(io,[fwrite/1,fwrite/2]).
-export([start/0]).

start() ->
PersonTuple = {lily,24,{blue,25}},  % 这里的 lily 或者 blue 不能用大写开头
fwrite(“learn tuple in erlang :~p~n “,[PersonTuple]).

list 和 tuple 还可以互转,搞得人懵逼。

 

-module(tuple_learn).
-import(io,[fwrite/1,fwrite/2,fwrite/3]).
-export([start/0]).

start() ->
PersonTuple = {lily,24,{blue,25}},
fwrite(“learn tuple in erlang :~p~n “,[PersonTuple]),

% is_tuple
fwrite(“judge is_tuple : ~w~n”,[is_tuple(PersonTuple)]),

% list_to_tuple
Lit1 = [2,3,5,7,11],
Tuple1 = list_to_tuple(Lit1),
fwrite(“list ~p to tuple result : ~p~n”,[Lit1,Tuple1]),

% tuple_to_list
NewList = tuple_to_list(PersonTuple),
fwrite(” new list ~p covert by tuple : ~p~n”,[NewList,PersonTuple])
.

最后输出

➜ erl -noshell -s tuple_learn start -s init stop
learn tuple in erlang :{lily,24,{blue,25}}
judge is_tuple : true
list [2,3,5,7,11] to tuple result : {2,3,5,7,11}
new list [lily,24,{blue,25}] covert by tuple : {lily,24,{blue,25}}

真的是很神奇,谁能告诉我,他Erlang的类型为啥这么个样子运行的?凭啥可以这样?