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';
 
// wordsreverseString, reverseEachWord, reverseWordOrder :: String -> [String]
const words = s => s.split(/\s+/);
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 =>
wordOrderReversed:x => unwords(reversef(words(strPhrasex)));
 
 
// 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());
 
// mapunlines :: (a -> b) -> [aString] -> [b]String
const mapunlines = (f, xs) => xs.mapjoin(f'\n');
 
// unwords :: [String] -> String
const unwords = xs => xs.join(' ');
 
// TESTwords :: String -> [String]
//const showwords ::= as -=> Strings.split(/\s+/);
const show = x => JSON.stringify(x, null, 2);
 
const strPhrase = 'rosetta code phrase reversal';
 
// TEST ------------------------------------------------------------------
return showunlines({
reversedString: reverse(strPhrase),
ap([
eachWordReversed: unwords(map(reverse, words(strPhrase))),
reverseString,
wordOrderReversed: unwords(reverse(words(strPhrase)))
reverseEachWord,
});
reverseWordOrder
const strPhrase = ' ], ["rosetta code phrase reversal';"])
);
})();</lang>
 
{{Out}}
"reversedString": "<pre>lasrever esarhp edoc attesor",
<pre>{
"eachWordReversed": "attesor edoc esarhp lasrever",
"reversedString": "lasrever esarhp edoc attesor",
"wordOrderReversd": "reversal phrase code rosetta"</pre>
"eachWordReversed": "attesor edoc esarhp lasrever",
"wordOrderReversd": "reversal phrase code rosetta"
}</pre>
 
=={{header|jq}}==
9,655

edits