From bde95f208ffb41631ad621ce1505f0086b42ccd2 Mon Sep 17 00:00:00 2001 From: Max Cahill Date: Fri, 20 Sep 2024 15:38:52 +1000 Subject: [PATCH] added functional.map_pairs --- functional.lua | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/functional.lua b/functional.lua index 3c19e27..2232889 100644 --- a/functional.lua +++ b/functional.lua @@ -318,6 +318,24 @@ end functional.map_chain = functional.chain +--maps a sequence {a, b, c, d} -> { f(a, b), f(a, c), f(a, d), f(b, c), f(b, d), f(c, d) } +-- ie all distinct pairs are mapped, useful for any N^2 dataset (eg finding neighbours) + +function functional.map_pairs(t, f) + local result = {} + for i = 1, #t do + for j = i+1, #t do + local a = t[i] + local b = t[j] + local v = f(a, b) + if v ~= nil then + table.insert(result, v) + end + end + end + return result +end + ----------------------------------------------------------- --generating data