Greatest subsequential sum: Difference between revisions

m
→‎JS Functional: (Adjusted type signature of main function)
m (→‎{{header|AppleScript}}: Updated primitives – max and gt)
m (→‎JS Functional: (Adjusted type signature of main function))
Line 1,597:
 
===Functional===
Linear approach, deriving anboth accumulatinglist foldand oversum thein inputa listsingle accumulating fold.
 
<lang JavaScript>(() => {
 
// maxSubseq :: [Int] -> (Int, [Int])
const maxSubseq = xs =>
snd(xs.reduce((tpl, x) => {
const [m1, m2] = Array.from(fst(tpl[0])),
high = max(
Tuple(0, []),
Tuple(m1 + x, m2.concat(x))
);
return Tuple(high, max(snd(tpl[1]), high));
}, Tuple(Tuple(0, []), Tuple(0, [])))[1][1]);
 
 
// TEST -----------------------------------------------
// main :: IO ()
const main = () => {
const mx = maxSubseq([-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1]);
showLog(...apsnd([idmx), sum], [fst(mx))
 
}
maxSubseq([-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1])
 
]));
// [3,5,6,-2,-1,4] -> 15
 
Line 1,626 ⟶ 1,624:
// GENERIC FUNCTIONS ----------------------------------
 
// ap (<*>)fst :: [(a ->, b)] -> [a] -> [b]
const apfst = (fs, xs)tpl => //tpl[0];
fs.reduce((a, f) => a.concat(
xs.reduce((a, x) => a.concat([f(x)]), [])
), []);
 
// gt :: Ord a => a -> a -> Bool
Line 1,637 ⟶ 1,632:
x[0] > y[0]
) : (x > y);
 
// id :: a -> a
const id = x => x;
 
// max :: Ord a => a -> a -> a
Line 1,652 ⟶ 1,644:
);
 
// sumsnd :: [Num](a, b) -> Numb
const sumsnd = xstpl => xs.reduce((a, x) => a + x, 0)tpl[1];
 
// Tuple (,) :: a -> b -> (a, b)
9,659

edits