Split a character string based on change of character: Difference between revisions
Content deleted Content added
→JS ES6: updated groupBy primitive ( redrafted as a fold, rather than an explicit recursion with 'span' ) |
→{{header|AppleScript}}: ( updated groupBy primitive – using a fold, rather than explicit recursion with span) |
||
Line 52: | Line 52: | ||
-- groupBy :: (a -> a -> Bool) -> [a] -> [[a]] |
-- groupBy :: (a -> a -> Bool) -> [a] -> [[a]] |
||
on groupBy(f, xs) |
on groupBy(f, xs) |
||
set |
set mf to mReturn(f) |
||
script enGroup |
|||
⚫ | |||
on lambda(a, x) |
|||
set h to cond(length of (active of a) > 0, item 1 of active of a, missing value) |
|||
⚫ | |||
if h is not missing value and mf's lambda(h, x) then |
|||
{active:(active of a) & x, sofar:sofar of a} |
|||
else |
|||
{active:{x}, sofar:(sofar of a) & {active of a}} |
|||
⚫ | |||
end if |
|||
end lambda |
|||
set {ys, zs} to span(matchPrevious, tail(xs)) |
|||
⚫ | |||
set lstGroup to {{x} & ys} |
|||
if length of xs > 0 then |
|||
set dct to foldl(enGroup, {active:{item 1 of xs}, sofar:{}}, tail(xs)) |
|||
sofar of dct & cond(length of (active of dct) > 0, {active of dct}, {}) |
|||
⚫ | |||
lstGroup |
|||
end if |
|||
else |
else |
||
{} |
{} |
||
Line 76: | Line 74: | ||
end groupBy |
end groupBy |
||
⚫ | |||
-- Span of unbroken predicate matches at left, returned with remainder |
|||
on foldl(f, startValue, xs) |
|||
⚫ | |||
on span(f, xs) |
|||
set lng to length of xs |
|||
set i to 0 |
|||
tell mReturn(f) |
tell mReturn(f) |
||
⚫ | |||
⚫ | |||
set lng to length of xs |
|||
repeat with i from 1 to lng |
|||
⚫ | |||
end repeat |
end repeat |
||
⚫ | |||
end tell |
end tell |
||
end foldl |
|||
if i > 0 then |
|||
-- cond :: Bool -> a -> a -> a |
|||
on cond(bool, f, g) |
|||
{items 1 thru i of xs, (items (i + 1) thru -1 of xs)} |
|||
if bool then |
|||
f |
|||
end if |
|||
else |
else |
||
g |
|||
end if |
end if |
||
end |
end cond |
||
-- intercalate :: Text -> [Text] -> Text |
-- intercalate :: Text -> [Text] -> Text |