请记住,您在 Erlang 中有通用比较规则,这意味着您可以比较字符串 "Alice" 和 "Al",因为它们只是列表。
现在进入有趣的部分:
table = :ets.new(:table, [:protected, :set])
:ets.insert(table, {1, "Alice", "Dannings"})
:ets.insert(table, {2, "Ali", "Aaqib"})
:ets.insert(table, {3, "Bob", "Dannings"})
:ets.insert(table, {4, "Amanda", "Clarke"})
:ets.insert(table, {5, "Al", "Clarke"})
# now let's explore elixir comparison rules
"Alice" >= "Al"
"Alice" < "Am"
# based on rules above we can make a selector which will be equivalent to starts_with?
selector = :ets.fun2ms(
fn({_, x, _} = y) # match all three element tuples
when # where
x >= "Al" and x < "Am" # second element is greater or equal to "Al" and less than "Am" ("m" is the next letter in the alphabet)
-> y end)
:ets.select(table, selector)
#[{1, "Alice", "Dannings"}, {2, "Ali", "Aaqib"}, {5, "Al", "Clarke"}]
虽然你可以通过字符串的开头“搜索”,但这很 hacky。
如果您想在运行时使用它,您必须在模块开头设置@compile {:parse_transform, :ms_transform} 或使用https://github.com/ericmj/ex2ms 之类的库来确保正确生成匹配规范(选择器)。