Write an Elixir function that uses Bitwise operators to implement a bloom filter.
- User
Write an Elixir function that uses
Bitwiseoperators to implement a bloom filter. Assistant
Write an Elixir function that uses Bitwise operators to implement a bloom filter.
1. Understand the Goal: The user wants an Elixir function (or module) that implements a Bloom Filter using Bitwise operators.
What is a Bloom Filter?
add operation: Hash the item times, set the bits at the resulting indices to 1.has operation: Hash the item times, check if all bits at the resulting indices are 1.Elixir Implementation Details:
:array (okay, but less idiomatic for bitwise manipulation directly).<<0, 0, ...>>). This is good, but setting a bit requires pattern matching or constructing a new binary, which can be slightly verbose.Bitwise.bsl(1, index) sets a bit. Bitwise.bor combines them. Bitwise.band checks them. This is the most "Bitwise" approach and highly efficient for the specific request.Drafting the Module Structure:
defmodule BloomFilter do
use Bitwise
defstruct [:size, :bits, :hash_count]
def new(size, hash_count) do
%__MODULE__{size: size, bits: 0, hash_count: hash_count}
end
def add(filter, item) do
# Calculate indices
# Update bits
end
def member?(filter, item) do
# Calculate indices
# Check bits
end
end
Refining the Bitwise Logic (Integer approach):
bits = bits ||| (1 <<< index)(bits &&& (1 <<< index)) != 0Refining the Hashing Logic:
seed1 and seed2.:erlang.phash2({item, seed}).Writing the Code:
defmodule BloomFilter do use Bitwise ... endsize, num_hashes, bitfield.bitfield to 0.num_hashes integers.
defp get_indices(item, size, k) do
# Double hashing strategy
h1 = :erlang.phash2(item, size)
h2 = :erlang.phash2({item, :salt}, size)
Enum.map(0..(k-1), fn i -> rem(h1 + i * h2, size) end)
end
def add(%__MODULE__{bits: bits, size: size, num_hashes: k} = filter, item) do
indices = get_indices(item, size, k)
new_bits = Enum.reduce(indices, bits, fn idx, acc ->
acc ||| (1 <<< idx)
end)
%{filter | bits: new_bits}
end
def member?(%__MODULE__{bits: bits, size: size, num_hashes: k}, item) do
indices = get_indices(item, size, k)
Enum.all?(indices, fn idx ->
(bits &&& (1 <<< idx)) != 0
end)
end
Edge Case Consideration:
1 <<< idx is fine.band, bor, bsl.Refining the Code for Presentation:
use Bitwise is included.Self-Correction/Alternative during drafting:
<<0::size(size)>>.bor, band, bsl) is cleaner code for a high-level language example and leverages Elixir's immutable arbitrary precision integers effectively. I will stick to the Integer approach but mention why (it's idiomatic for bit manipulation logic in Elixir).Final Code Structure:
defmodule BloomFilter do
use Bitwise
defstruct [:size, :num_hashes, :bits]
# Constructor
def new(size, num_hashes) when size > 0 and num_hashes > 0 do
%__MODULE__{size: size, num_hashes: num_hashes, bits: 0}
end
# Add
def put(%__MODULE__{} = filter, item) do
indices = get_indices(filter, item)
new_bits = Enum.reduce(indices, filter.bits, fn idx, acc ->
# Set bit at idx: acc OR (1 shifted left by idx)
acc ||| (1 <<< idx)
end)
%{filter | bits: new_bits}
end
# Check
def member?(%__MODULE__{} = filter, item) do
indices = get_indices(filter, item)
Enum.all?(indices, fn idx ->
# Check bit at idx: (acc AND (1 shifted left by idx)) > 0
(filter.bits &&& (1 <<< idx)) > 0
end)
end
# Helper to generate k indices using double hashing
defp get_indices(%__MODULE__{size: size, num_hashes: k}, item) do
# Use two independent hashes to generate k unique-ish indices
h1 = :erlang.phash2(item, size)
h2 = :erlang.phash2({item, 1}, size) # Salt for second hash
Enum.map(0..(k - 1), fn i ->
rem(h1 + i * h2, size)
end)
end
end
Review against constraints:
Bitwise? Yes (|||, &&&, <<< or explicit bor, band, bsl). I prefer the infix operators or the explicit functions. Explicit functions are often clearer for tutorials. Let's use the explicit Bitwise module functions for clarity, or use import Bitwise to allow infix. The prompt asks to use Bitwise operators. use Bitwise imports them.Adding explanation: Explain the trade-offs (Integer vs Binary), the hashing strategy (Double Hashing), and the logic.
Final Polish: Ensure syntax is correct. rem handles the modulo for negative numbers? phash2 returns positive integers. h1 + i*h2 could theoretically exceed integer limits, but Elixir handles bignums. The modulo wraps it back to size.
One small correction: phash2(term, range) returns 0..range-1. This is safer than rem.
Let's write the solution. Here is an implementation of a Bloom Filter in Elixir.
This implementation uses an Integer to represent the bit array. Elixir handles arbitrary-precision integers automatically, meaning this filter can scale to millions of bits without requiring a fixed-size binary buffer.
defmodule BloomFilter do
use Bitwise
defstruct [:size, :num_hashes, :bits]
@doc """
Initializes a new Bloom Filter.
"""
def new(size, num_hashes) do
%__MODULE__{
size: size,
num_hashes: num_hashes,
bits: 0
}
end
@doc """
Adds an item to the filter.
"""
def add(%__MODULE__{bits: bits} = filter, item) do
indices = get_indices(filter, item)
# Iterate over all calculated indices and set the corresponding bit to 1.
# We use Bor (Bitwise OR) to merge the new bits into the existing state.
new_bits = Enum.reduce(indices, bits, fn index, acc ->
mask = 1 <<< index
acc ||| mask
end)
%{filter | bits: new_bits}
end
@doc """
Checks if an item is possibly in the set.
Returns `true` if the item might be in the set.
Returns `false` if the item is definitely NOT in the set.
"""
def member?(%__MODULE__{bits: bits} = filter, item) do
indices = get_indices(filter, item)
# Iterate over all indices and verify the bit is set.
# We use Band (Bitwise AND) to check specific bits.
Enum.all?(indices, fn index ->
mask = 1 <<< index
(bits &&& mask) != 0
end)
end
# --- Private Helpers ---
# Generates a list of unique bit indices for a given item.
# We use a "Double Hash" technique to simulate k different hash functions
# without requiring k separate hashing libraries.
defp get_indices(%__MODULE__{size: size, num_hashes: num_hashes}, item) do
# Create two base hashes
hash1 = :erlang.phash2(item, size)
hash2 = :erlang.phash2({item, :salt}, size)
Enum.map(0..(num_hashes - 1), fn i ->
# Combine hashes to produce the i-th index
rem(hash1 + i * hash2, size)
end)
end
end
bits field holds the state. Because Elixir integers automatically expand, bits acts as an infinitely long bitfield where we only consume as much memory as the highest bit index we set.add/2):
<<<.3, 1 <<< 3 produces the binary 01000 (decimal 8).||| (Bitwise OR). If the bit was already 1, it stays 1. If it was 0, it becomes 1.member?/2):
<<<.&&& (Bitwise AND). This masks out all other bits.!= 0), the bit was set.get_indices generates num_hashes different indices. It uses :erlang.phash2 (a fast hash function) and a technique called "double hashing" to generate variations based on the item.You can copy the code into an Elixir file (e.g., bloom.ex) or iex:
# 1. Create a filter with a bit-depth of 100 and 3 hash functions
bf = BloomFilter.new(100, 3)
# 2. Add some items
bf = BloomFilter.add(bf, "apple")
bf = BloomFilter.add(bf, "banana")
# 3. Check for existence
IO.puts("Has 'apple'? #{BloomFilter.member?(bf, "apple")}") # true
IO.puts("Has 'banana'? #{BloomFilter.member?(bf, "banana")}") # true
# 4. Check for a non-existent item
# Note: There is a small statistical chance this returns true (False Positive)
IO.puts("Has 'grape'? #{BloomFilter.member?(bf, "grape")}") # false
:erlang.phash2 or :crypto.hash. Since it's an example, :erlang.phash2 is fast and built-in.h1 = :erlang.phash2(item, size) (Wait, phash2 takes a range).h2 = :erlang.phash2({item, :second_hash}, size) (Wait, phash2/2 limits the range, which is convenient).Let's verify phash2 range: :erlang.phash2(term, range) returns 0..range-1. This is perfect.