Split a character string based on change of character: Difference between revisions
Content added Content deleted
(Add Forth solution) |
(→JS ES6: Updated primitives) |
||
Line 514: | Line 514: | ||
{{Trans|Haskell}} |
{{Trans|Haskell}} |
||
<lang JavaScript>(() => { |
<lang JavaScript>(() => { |
||
// GENERIC FUNCTIONS ------------------------------------------------------ |
|||
'use strict'; |
|||
// concat :: [[a]] -> [a] | [String] -> String |
|||
// GENERIC FUNCTIONS |
|||
const concat = xs => |
|||
xs.length > 0 ? (() => { |
|||
const unit = typeof xs[0] === 'string' ? '' : []; |
|||
return unit.concat.apply(unit, xs); |
|||
})() : []; |
|||
// group :: Eq a => [a] -> [[a]] |
// group :: Eq a => [a] -> [[a]] |
||
Line 528: | Line 533: | ||
h = a.active.length > 0 ? a.active[0] : undefined, |
h = a.active.length > 0 ? a.active[0] : undefined, |
||
blnGroup = h !== undefined && f(h, x); |
blnGroup = h !== undefined && f(h, x); |
||
return { |
return { |
||
active: blnGroup ? a.active.concat(x) : [x], |
active: blnGroup ? a.active.concat([x]) : [x], |
||
sofar: blnGroup ? a.sofar : a.sofar.concat([a.active]) |
sofar: blnGroup ? a.sofar : a.sofar.concat([a.active]) |
||
}; |
}; |
||
Line 543: | Line 547: | ||
const intercalate = (s, xs) => xs.join(s); |
const intercalate = (s, xs) => xs.join(s); |
||
// map :: (a -> b) -> [a] -> [b] |
|||
⚫ | |||
const map = (f, xs) => xs.map(f); |
|||
⚫ | |||
.map(x => x.join(''))); |
|||
// show :: a -> String |
|||
const show = (...x) => |
|||
JSON.stringify.apply( |
|||
null, x.length > 1 ? [x[0], null, x[1]] : x |
|||
); |
|||
// stringChars :: String -> [Char] |
|||
const stringChars = s => s.split(''); |
|||
// TEST ------------------------------------------------------------------- |
|||
return show( |
|||
intercalate(", ", |
|||
⚫ | |||
⚫ | |||
); |
|||
// -> "g, HHH, 5, YY, ++, ///, \\" |
// -> "g, HHH, 5, YY, ++, ///, \\" |
||
})();</lang> |
})();</lang> |
||
{{Out}} |
{{Out}} |
||
<pre>g, HHH, 5, YY, ++, ///, \</pre> |
<pre>g, HHH, 5, YY, ++, ///, \</pre> |