Erlang列表过滤问题
我有一个记录,其中一个字段是列表:
-record(state, {
rcpt :: list()
}).
Rcpt 字段有一些值 =
[“本地主机”,“管理员”]
我需要过滤此列表。例如我需要字段 localhost。
我尝试:
List = lists:filter(fun(X) -> LocalHost =:= X end, State#state.rcpt),
但列表是空的。
我做错了什么?
我不明白。看:
io:format(State#state.rcpt),
%% output: localhost
HaveRcpt = lists:member("localhost", State#state.rcpt ),
io:format(HaveRcpt);
%% output false
但是如果我使用:
io:format(State#state.rcpt),
HaveRcpt = lists:member("localhost", lists:nth(1,State#state.rcpt) ),
io:format(HaveRcpt);
%% true
谢谢。
I have record in which one field is list:
-record(state, {
rcpt :: list()
}).
Rcpt field has some values =
["localhost", "admin"]
I need filter this list. For example i need field localhost.
I try:
List = lists:filter(fun(X) -> LocalHost =:= X end, State#state.rcpt),
but List is empty.
What's wrong i do?
I don't understand it. Look:
io:format(State#state.rcpt),
%% output: localhost
HaveRcpt = lists:member("localhost", State#state.rcpt ),
io:format(HaveRcpt);
%% output false
But if i use:
io:format(State#state.rcpt),
HaveRcpt = lists:member("localhost", lists:nth(1,State#state.rcpt) ),
io:format(HaveRcpt);
%% true
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您已经拥有完整的值,那么您的真正目标不是要查看该值是否只是列表中的成员吗?
如果该
值可能因任何原因重复多次并且您想要所有这些字段,则可以使用类似这样的列表:filter/2。
您在示例中引入了变量 LocalHost。这必须是与您的元素(“localhost”、“admin”)完全相同的值,才能返回空列表以外的任何内容。
If you already have the full value isn't your real objective to see if that value is just a member of the list or not?
That may be used like
If the value may be repeated several times for any reasons and you want all of those fields, you may use the lists:filter/2 like this.
You introduced a variable LocalHost in your example. This must be the exact value as your element ("localhost","admin") to ever return anything else then a empty list.
首先,最好为 rcpt 字段设置默认值:
然后需要正确设置 rcpt 字段值(最好将此操作封装在设置函数中):
然后您可以按预期使用 lists:member 的所有内容:
Firstly, it's better to set default value for rcpt field:
Then you need to set rcpt field value correctly (it's better to encapsulate this operation in a setup function):
And after all that you can use lists:member as expected:
如果
您的 State#state.rcpt 必须包含 [["localhost"]|_]
如果您有正确的内容,它将按预期工作
If
then your State#state.rcpt have to contain [["localhost"]|_]
If you would have correct content it would work as expected