我是Erlang的新手.我只想将值重新赋值给字符串变量:
get_alert_body(Packet) ->
BodyElement = element(8,Packet),
Body = "my text",
Els = xmpp:get_els(Packet),
lists:foreach(fun(El) ->
ElementName = io_lib:format("~s",[xmpp:get_name(El)]),
IsFile = string:equal(ElementName,"fileType"),
if
IsFile ->
FileType = fxml:get_tag_cdata(El),
IsPhoto = string:equal(FileType,"photo"),
IsVideo = string:equal(FileType,"video"),
if
IsPhoto ->
%% if it gets to this I would like to return "my photo"
Body = "my photo";
IsVideo ->
%% else if it gets to this I would like to return "my video"
Body = "my video";
true ->
%% otherwise I would like to return "my text"
ok
end;
true ->
ok
end
end, Els),
Body.
Run Code Online (Sandbox Code Playgroud)
但我得到这个错误:
error,{badmatch,"test2"}
Run Code Online (Sandbox Code Playgroud)
即使我做的事情如下:
A = "test1",
A = "test2",
Run Code Online (Sandbox Code Playgroud)
我犯了同样的错误.
我很感激你的帮助.
你不能.Erlang有一个名为"单一赋值"的功能,这意味着在第一次分配变量后,您无法更改变量的值.如果你尝试这样做,它就会变成一个模式匹配,而你会得到一个badmatch错误,就像你试图做的那样"test1" = "test2".
您的示例可以写为:
A =
if
Condition ->
"test2";
true ->
"test1"
end
Run Code Online (Sandbox Code Playgroud)
有关单一作业的更多信息,请参阅此问题及其答案.
在您的扩展示例中,您可以通过折叠实现您要做的事情.也就是说,给定一个列表和一个称为"累加器"的附加值,遍历列表并为每个元素调用一个函数,并让该函数的返回值为新的累加器 - 并在最后返回累加器.
使用lists:foldl/3的是,像这样的:
get_alert_body(Packet) ->
BodyElement = element(8,Packet),
DefaultBody = "my text",
Els = xmpp:get_els(Packet),
lists:foldl(fun(El, Body) ->
ElementName = io_lib:format("~s",[xmpp:get_name(El)]),
IsFile = string:equal(ElementName,"fileType"),
if
IsFile ->
FileType = fxml:get_tag_cdata(El),
IsPhoto = string:equal(FileType,"photo"),
IsVideo = string:equal(FileType,"video"),
if
IsPhoto ->
%% if it gets to this I would like to return "my photo"
"my photo";
IsVideo ->
%% else if it gets to this I would like to return "my video"
"my video";
true ->
%% otherwise return the existing value
Body
end;
true ->
ok
end
end, DefaultBody, Els).
Run Code Online (Sandbox Code Playgroud)