Skip to content

Instantly share code, notes, and snippets.

@ajparsons
Created September 13, 2025 14:43
Show Gist options
  • Select an option

  • Save ajparsons/5eecb23c6473e9681d9a0471d5fb2c5a to your computer and use it in GitHub Desktop.

Select an option

Save ajparsons/5eecb23c6473e9681d9a0471d5fb2c5a to your computer and use it in GitHub Desktop.
library(rextendr)
rust_code <- "
fn mean_min_abs_distance(voters: Vec<f64>, parties: Vec<f64>) -> f64 {
let mut total_min = 0.0;
for &v in &voters {
let min_dist = parties
.iter()
.map(|&p| (v - p).abs())
.fold(f64::INFINITY, |a, b| a.min(b));
total_min += min_dist;
}
total_min / (voters.len() as f64)
}
"
rust_function(rust_code, quiet = TRUE, profile = "release")
# Example usage in R
set.seed(236435)
n_voters <- 1e4
voters <- rnorm(n_voters)
n_sims <- 100
library(tictoc)
tic()
out <- sapply(1:6, function(n_parties) {
replicate(n_sims, {
parties <- rnorm(n_parties)
mean_min_abs_distance(voters, parties)
})
})
toc()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment