Equilibrium index: Difference between revisions
→ES6 Functional: Tidied, updated primitives and output format.
Deadmarshal (talk | contribs) (Added Lua language for this task) |
(→ES6 Functional: Tidied, updated primitives and output format.) |
||
Line 1,401:
<lang javascript>(() => {
// ---------------- EQUILIBRIUM INDEX ----------------
// equilibriumIndices :: [Int] -> [Int]
const equilibriumIndices = xs =>
zip
scanr1(add)(xs)
)
(a, xy, i) => xy[0] === xy[1] ? (
[i, ...a]
) : a, []
// ----------------------
const main = () =>
console.log(JSON.stringify([▼
[-7, 1, 5, 2, -4, 3, 0],
[2, 4, 6],
Line 1,421 ⟶ 1,427:
[1],
[]
].map(
// -> [[3, 6], [], [1], [0, 1, 2, 3, 4, 5, 6], [0], []]▼
equilibriumIndices
.join("\n");
// ----------------
// Tuple (,) :: a -> b -> (a, b)▼
const Tuple = a =>▼
▲ b => ({
type: 'Tuple',▼
▲ '0': a,
'1': b,▼
▲ });
// add (+) :: Num a => a -> a -> a
Line 1,441:
// Curried addition.
b => a + b;
const compose = (...fs) =>
// composition of all the functions in fs.
fs.reduce(
(f, g) => x => f(g(x)),
// scanl :: (b -> a -> b) -> b -> [a] -> [b]
const scanl = f => startValue => xs =>
//
//
v => xs => xs.reduce((a, x) => {▼
const v = f(a[0])(x);
return Tuple(v)(a[1].concat(v));▼
}, Tuple(v)([v]))[1];▼
}, [startValue, [startValue]])[1];
▲ const scanr = f =>
▲ // values, building from the right.
▲ const v = f(x)(a[0]);
// scanl1 :: (a -> a -> a) -> [a] -> [a]
const scanl1 = f =>
// scanl1 is a variant of scanl that has no
//
xs => xs.length > 0 ? (
scanl(f)(
Line 1,472 ⟶ 1,473:
)(xs.slice(1))
) : [];
// scanr :: (a -> b -> b) -> b -> [a] -> [b]
const v = f(x)(a[0]);
}, [startValue, [startValue]]
// scanr1 :: (a -> a -> a) -> [a] -> [a]
Line 1,483 ⟶ 1,496:
)(xs.slice(0, -1))
) : [];
// zip :: [a] -> [b] -> [(a, b)]
const zip = xs =>
// The paired members of xs and ys, up to
// the length of the shorter of the two lists.
ys => Array.from({
length: Math.min(xs.length, ys.length)
}, (_, i) =>
// MAIN ---
Line 1,494 ⟶ 1,510:
})();</lang>
{{Out}}
<pre>
[]
[1]
[0,1,2,3,4,5,6]
[0]
[]</pre>
=={{header|jq}}==
|