You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Elixir中:ets.select_count返回0但length(:ets.select)结果正常问题排查

ETS select_count返回0的原因及修复方案

问题出在:ets.select_count/2对匹配规范(MatchSpec)的结果部分有特殊要求:它仅会统计**返回布尔值true**的匹配条目,非布尔值会被当作false处理,不计入统计。

你的MatchSpec是[{{:'$1', "a"}, [], [:'$1']}],其中结果部分返回的是第一个匹配元素:'$1'(即字符串"b"),并非布尔值。因此所有匹配的条目都被判定为false,最终统计结果为0。

而:ets.select/2的逻辑是返回所有匹配条目对应的结果值,所以它能正确返回["b"],length/1自然得到预期的1。

修复方案

修改MatchSpec的结果部分为[true],让匹配到的条目返回true,:ets.select_count/2就会正确统计数量:

table = :ets.new(:tbl, [])
:ets.insert(table, {"a", "b"})
:ets.insert(table, {"b", "a"})
IO.puts("select_count: #{:ets.select_count(table, [{{:'$1', "a"}, [], [true]}])}") # 输出1
IO.puts("length(select): #{length(:ets.select(table, [{{:'$1', "a"}, [], [:'$1']}]))}") # 输出1

如果需要添加守卫条件(比如过滤特定规则的条目),也可以正常加入,例如只统计第一个元素长度大于1的匹配条目:

:ets.select_count(table, [{{:'$1', "a"}, [{:>, {:string_length, :'$1'}, 1}], [true]}])

内容的提问来源于stack exchange,提问作者dprofe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 05:58:24