Phrase reversals: Difference between revisions
→JS ES6: Reshaped to foreground the core.
(→{{header|Haskell}}: Rearranged a little to foreground the core. Added type signatures.) |
(→JS ES6: Reshaped to foreground the core.) |
||
Line 1,034:
===ES6===
<lang JavaScript>(() => {
'use strict'
//
const
reverseString = s => reverse(s),
reverseEachWord = s => wordLevel(map(reverse))(s),
// unwords :: [String] -> String▼
const unwords = xs => xs.join(' ');▼
reverseWordOrder = s => wordLevel(reverse)(s);
// wordLevel :: ([String] -> [String]) -> String -> String
const wordLevel = f =>
// GENERIC FUNCTIONS -----------------------------------------------------
// A list of functions applied to a list of arguments
// <*> :: [(a -> b)] -> [a] -> [b]
const ap = (fs, xs) => //
[].concat.apply([], fs.map(f => //
[].concat.apply([], xs.map(x => [f(x)]))));
// 2 or more arguments
// curry :: Function -> Function
const curry = (f, ...args) => {
const go = xs => xs.length >= f.length ? (f.apply(null, xs)) :
function () {
return go(xs.concat(Array.from(arguments)));
};
return go([].slice.call(args, 1));
// map :: (a -> b) -> [a] -> [b]
const map = curry((f, xs) => xs.map(f));
// reverse :: [a] -> [a]
const reverse = curry(xs =>
typeof xs === 'string' ? (
xs.split('')
Line 1,049 ⟶ 1,077:
.join('')
) : xs.slice(0)
.reverse());
//
const
▲ // unwords :: [String] -> String
▲ const unwords = xs => xs.join(' ');
//
const strPhrase = 'rosetta code phrase reversal';▼
// TEST ------------------------------------------------------------------
return
ap([
reverseString,
▲ wordOrderReversed: unwords(reverse(words(strPhrase)))
reverseEachWord,
▲ });
reverseWordOrder
);
})();</lang>
{{Out}}
▲ "reversedString": "lasrever esarhp edoc attesor",
▲ "eachWordReversed": "attesor edoc esarhp lasrever",
▲ "wordOrderReversd": "reversal phrase code rosetta"
=={{header|jq}}==
|