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

Content added Content deleted
(→‎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:
-- groupBy :: (a -> a -> Bool) -> [a] -> [[a]]
on groupBy(f, xs)
set lngmf to length of xsmReturn(f)
if lng > 0 then
script enGroup
set x to item 1 of xs
seton mflambda(a, to mReturn(fx)
set h to cond(length of (active of a) > 0, item 1 of active of a, missing value)
script matchPrevious
onif h is not missing value and mf's lambda(yh, x) then
mf's lambda{active:(active of a) & x, y)sofar:sofar of a}
end lambdaelse
{active:{x}, sofar:(sofar of a) & {active of a}}
end script
end if
end lambda
set {ys, zs} to span(matchPrevious, tail(xs))
end script
set lstGroup to {{x} & ys}
if length of xs if zs ≠> {}0 then
set dct to foldl(enGroup, lstGroup{active:{item &1 groupBy(mfof xs}, zssofar:{}}, tail(xs))
sofar of dct & cond(length of (active of dct) > 0, {active of dct}, {})
else
lstGroup
end if
else
{}
Line 76 ⟶ 74:
end groupBy
 
-- spanfoldl :: (a -> Boolb -> a) -> [a] -> ([ab],[ -> a])
-- Span of unbroken predicate matches at left, returned with remainder
on foldl(f, startValue, xs)
-- span :: (a -> Bool) -> [a] -> ([a],[a])
on span(f, xs)
set lng to length of xs
set i to 0
tell mReturn(f)
set xv to item 1 of xsstartValue
repeat while i < lng and lambda(item (i + 1) of xs)
set ilng to ilength +of 1xs
repeat with i from 1 to lng
repeat while i < lngset andv to lambda(v, item (i +of 1)xs, ofi, xs)
end repeat
return v
end tell
end foldl
 
if i > 0 then
-- cond :: Bool -> a -> a if-> i < lng thena
on cond(bool, f, g)
{items 1 thru i of xs, (items (i + 1) thru -1 of xs)}
if bool elsethen
{xs, {}}f
end if
else
{{}, xs}g
end if
end spancond
 
-- intercalate :: Text -> [Text] -> Text