How to implement the inverse "intercalate" (dividing a line into figures by a character) using functions from the "base"?

I wanted to split a string into newline, and I was surprised that I could not find the inverse function intercalate "\n". That is, a function that breaks a string into parts into new lines (or according to some other predicate).

Please note that linesthey wordsare doing something else. for example

intercalate "\n" (lines "a\n") == "a"

The section library has a similar functional function splitOn. I could also write such a function directly:

splitOn :: (a -> Bool) -> [a] -> [[a]]
splitOn p = map reverse . g []
  where
    g rs []                 = [rs]
    g rs (x:xs) | p x       = rs : g [] xs
                | otherwise = g (x : rs) xs

but I wonder if it could be built more easily using only functions from base .

+4
2

, " Prelude" , :

splitWhen p [] = [[]]
splitWhen p l  = uncurry (:) . fmap (splitWhen p . drop 1) . break p $ l

Functor (,) a Control.Arrow.second ( -), (ghci " " GHC.Base "), , Prelude, Haskell.

: base, . second fmap, , -, . unfoldr, Maybe , ( ):

import Control.Applicative ((<$>))
import Control.Arrow (second)
import Data.List (unfoldr)

splitWhen p = unfoldr (second check . break p <$>) . Just
  where
    check []       = Nothing
    check (_:rest) = Just rest

-- or cramming it into a single line with 'Data.Maybe.listToMaybe'
splitWhen' p =
  unfoldr (second (\rest -> tail rest <$ listToMaybe rest) . break p <$>) . Just
+5

- , , , -, unfoldr break, unfoldr Prelude.

, , , Prelude , , , , , . Prelude, -, : , , Haskell , , "" , Haskellers .

+5

All Articles