Shoelace formula for polygonal area: Difference between revisions
→{{header|JavaScript}}: Updated primitives, tidied.
(→{{header|Haskell}}: Tidied in terms of bimap) |
(→{{header|JavaScript}}: Updated primitives, tidied.) |
||
Line 836:
=={{header|JavaScript}}==
<lang javascript>(() => {
// ------- SHOELACE FORMULA FOR POLYGONAL AREA -------
// shoelaceArea :: [(Float, Float)] -> Float
const shoeLaceArea = vertices => abs(
uncurry(subtract)(
b => a[int(b)] + x[0][int(b)] * x[1][int(!b)]▼
)▼
);
}
▲ ),
)
)
Line 863 ⟶ 871:
[5, 6]
];
return
`${JSON.stringify(ps)} -> ${shoeLaceArea(ps)}`
};
Line 873 ⟶ 883:
// abs :: Num -> Num
const abs = x =>
// Absolute value of a given number
// ap :: (a -> b -> c) -> (a -> b) -> (a -> c)
const ap = f =>
// Applicative instance for functions.
Line 889 ⟶ 900:
// compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
const compose = (...fs) =>
// A function defined by the right-to-left
// composition of all the functions in fs.
fs.reduce(
(f, g) => x => f(g(x)),
Line 896 ⟶ 909:
// cycle :: [a] -> Generator [a]
const cycle = function*
// from which an arbitrary prefix
const lng = xs.length;
let i = 0;
while (true) {
yield
i = (1 + i) % lng;
}
};
a => xs => xs.reduce((x, y) => f(x)(y), a);▼
▲ 1
▲ ) : 0;
// length :: [a] -> Int
Line 922 ⟶ 929:
// the shorter argument when one is non-finite,
// like cycle, repeat etc
xs.length
) : Infinity;
▲ // to each element of xs.
Array.isArray(xs) ? (▼
▲ xs
) : xs.split('')▼
▲ ).map(f);
Line 948 ⟶ 944:
// A new list consisting of all
// items of xs except the first.
) : undefined
) : (take(1)(xs), xs);
Line 958 ⟶ 957:
// The first n elements of a list,
// string of characters, or stream.
xs =>
.constructor.constructor.name ? (
xs.slice(0, n)
) :
length: n
}, () => {
const x = xs.next();
return x.done ? [] : [x.value];
}).flat();
Line 973:
// A function over a pair, derived
// from a curried function.
const [x, y] = Boolean(args.length % 2) ? (
args
) :
▲ args[0]
return
return f(xy[0])(xy[1]);▼
};
//
const
▲ const
▲ lng = Math.min(length(xs), length(ys)),
▲ vs = take(lng)(ys);
▲ (x, i) => [x, vs[i]]
▲ );
▲ };
// MAIN ---
|