[Haskell-cafe] Missing join and split

Benja Fallenstein benja.fallenstein at gmail.com
Fri Dec 28 09:51:19 EST 2007


Hi all,

On Dec 28, 2007 12:38 PM, Andrew Coppin <andrewcoppin at btinternet.com> wrote:
> For joining you probably want some combination of intersperse and
> concat, e.g.
>
>   unlines = concat . intersperse "\n"

And that's what we have :-)

Data.List.intercalate :: [a] -> [[a]] -> [a]
Data.List.intercalate x = concat . intersperse x

> For splitting, do we split on a given character? A predicate? Do we keep
> the splitting character or throw it away? Do we generate empty sublists
> or elide them? Apparently nobody can agree on these points, and writing
> a function with all possible options would be very messy...

If you use intercalate to join, I would presume that you would want to
use an inverse of it to split. I'd write it like this:

split :: Eq a => [a] -> [a] -> [[a]]
split at xs | Just xs' <- stripPrefix at xs = [] : split at xs'
split at (x:xs) = (x:r) : rs where (r:rs) = split at xs
split at []     = [[]]

--with, if your version of the libraries is as old as mine and doesn't
have Data.List.stripPrefix,

stripPrefix (p:ps) (x:xs) | p == x = stripPrefix ps xs
stripPrefix []     xs              = Just xs
stripPrefix _      _               = Nothing

- Benja


More information about the Haskell-Cafe mailing list