Greatest subsequential sum: Difference between revisions
Content added Content deleted
m (→{{header|AppleScript}}: Updated primitives – max and gt) |
m (→JS Functional: (Adjusted type signature of main function)) |
||
Line 1,597: | Line 1,597: | ||
===Functional=== |
===Functional=== |
||
Linear approach |
Linear approach, deriving both list and sum in a single accumulating fold. |
||
<lang JavaScript>(() => { |
<lang JavaScript>(() => { |
||
// maxSubseq :: [Int] -> [Int] |
// maxSubseq :: [Int] -> (Int, [Int]) |
||
const maxSubseq = xs => |
const maxSubseq = xs => |
||
xs.reduce((tpl, x) => { |
snd(xs.reduce((tpl, x) => { |
||
const [m1, m2] = Array.from(tpl |
const [m1, m2] = Array.from(fst(tpl)), |
||
high = max( |
high = max( |
||
Tuple(0, []), |
Tuple(0, []), |
||
Tuple(m1 + x, m2.concat(x)) |
Tuple(m1 + x, m2.concat(x)) |
||
); |
); |
||
return Tuple(high, max(tpl |
return Tuple(high, max(snd(tpl), high)); |
||
}, Tuple(Tuple(0, []), Tuple(0, []))) |
}, Tuple(Tuple(0, []), Tuple(0, [])))); |
||
// TEST ----------------------------------------------- |
// TEST ----------------------------------------------- |
||
// main :: IO () |
// main :: IO () |
||
const main = () => |
const main = () => { |
||
⚫ | |||
showLog( |
showLog(snd(mx), fst(mx)) |
||
} |
|||
⚫ | |||
])); |
|||
// [3,5,6,-2,-1,4] -> 15 |
// [3,5,6,-2,-1,4] -> 15 |
||
Line 1,626: | Line 1,624: | ||
// GENERIC FUNCTIONS ---------------------------------- |
// GENERIC FUNCTIONS ---------------------------------- |
||
// |
// fst :: (a, b) -> a |
||
const |
const fst = tpl => tpl[0]; |
||
fs.reduce((a, f) => a.concat( |
|||
xs.reduce((a, x) => a.concat([f(x)]), []) |
|||
), []); |
|||
// gt :: Ord a => a -> a -> Bool |
// gt :: Ord a => a -> a -> Bool |
||
Line 1,637: | Line 1,632: | ||
x[0] > y[0] |
x[0] > y[0] |
||
) : (x > y); |
) : (x > y); |
||
// id :: a -> a |
|||
const id = x => x; |
|||
// max :: Ord a => a -> a -> a |
// max :: Ord a => a -> a -> a |
||
Line 1,652: | Line 1,644: | ||
); |
); |
||
// |
// snd :: (a, b) -> b |
||
const |
const snd = tpl => tpl[1]; |
||
// Tuple (,) :: a -> b -> (a, b) |
// Tuple (,) :: a -> b -> (a, b) |