Module:Math: Difference between revisions
Jump to navigation
Jump to search
Content added Content deleted
en>Mr. Stradivarius (get #expr without a frame, don't make unnecessary wrappers, and lazily initialise dependent modules, per protected edit request by User:Jackmcbarn) |
(simplify using a new binary_fold function, per protected edit request by User:Esquivalience) |
||
Line 49: | Line 49: | ||
end |
end |
||
local function |
local function fold(func, ...) |
||
-- Use a function on all supplied arguments, and return the result. The function must accept two numbers as parameters, |
-- Use a function on all supplied arguments, and return the result. The function must accept two numbers as parameters, |
||
-- and must return a number as an output. This number is then supplied as input to the next function call. |
-- and must return a number as an output. This number is then supplied as input to the next function call. |
||
Line 63: | Line 63: | ||
end |
end |
||
return ret, count |
return ret, count |
||
⚫ | |||
--[[ |
|||
Fold arguments by selectively choosing values (func should return when to choose the current "dominant" value). |
|||
]] |
|||
⚫ | |||
local value = fold((function(a, b) if func(a, b) then return a else return b end end), ...) |
|||
⚫ | |||
end |
end |
||
Line 190: | Line 198: | ||
return result |
return result |
||
end |
end |
||
--[[ |
--[[ |
||
Line 207: | Line 216: | ||
function p._max(...) |
function p._max(...) |
||
local max_value = binary_fold((function(a, b) return a > b end), ...) |
|||
⚫ | |||
if a > b then |
|||
return a |
|||
else |
|||
return b |
|||
end |
|||
⚫ | |||
local max_value = applyFuncToArgs(maxOfTwo, ...) |
|||
if max_value then |
if max_value then |
||
return max_value |
return max_value |
||
Line 239: | Line 241: | ||
function p._min(...) |
function p._min(...) |
||
local min_value = binary_fold((function(a, b) return a < b end), ...) |
|||
local function minOfTwo(a, b) |
|||
if a < b then |
|||
return a |
|||
else |
|||
return b |
|||
end |
|||
end |
|||
local min_value = applyFuncToArgs(minOfTwo, ...) |
|||
if min_value then |
if min_value then |
||
return min_value |
return min_value |
||
Line 270: | Line 265: | ||
function p._average(...) |
function p._average(...) |
||
local |
local sum, count = fold((function(a, b) return a + b end), ...) |
||
⚫ | |||
end |
|||
local sum, count = applyFuncToArgs(getSum, ...) |
|||
if not sum then |
if not sum then |
||
return 0 |
return 0 |
||
Line 362: | Line 354: | ||
return oldr |
return oldr |
||
end |
end |
||
local result, count = |
local result, count = fold(findGcd, ...) |
||
return result |
return result |
||
end |
end |