Jump to content

Split a character string based on change of character: Difference between revisions

({{header|Haskell}})
Line 30:
main :: IO ()
main = putStrLn $ intercalate ", " (group "gHHH5YY++///\\")</lang>
 
{{Out}}
<pre>g, HHH, 5, YY, ++, ///, \</pre>
 
=={{header|JavaScript}}==
{{Trans|Haskell}}
===ES6===
<lang JavaScript>(() => {
'use strict';
 
// GENERIC FUNCTIONS
 
// group :: Eq a => [a] -> [[a]]
const group = xs => groupBy((a, b) => a === b, xs);
 
// groupBy :: (a -> a -> Bool) -> [a] -> [[a]]
const groupBy = (f, xs) => {
const lng = xs.length;
 
if (lng > 0) {
const x = xs[0],
lstSpanRest = span(y => f(x, y), xs.slice(1)),
ys = lstSpanRest[0],
zs = lstSpanRest[1],
group = [(ys.length ? [x].concat(ys) : [x])];
 
return zs.length ? group.concat(groupBy(f, zs)) : group;
 
} else return [];
};
 
// Span of unbroken predicate matches at left, returned with remainder
// span :: (a -> Bool) -> [a] -> ([a],[a])
const span = (f, xs) => {
for (var i = 0, lng = xs.length;
(i < lng) && f(xs[i]); i++) {}
return [xs.slice(0, i), xs.slice(i)];
}
 
// intercalate :: String -> [a] -> String
const intercalate = (s, xs) => xs.join(s);
 
 
// TEST
return intercalate(", ", group("gHHH5YY++///\\".split(''))
.map(x => x.join('')));
 
// -> "g, HHH, 5, YY, ++, ///, \\"
})();</lang>
 
{{Out}}
9,659

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.