[Haskell-cafe] Separate a string into a list of strings

Clifford Beshers clifford.beshers at linspire.com
Tue Jun 13 01:44:35 EDT 2006


Well, I couldn't resist the puzzle.  Here are solutions using foldr and 
unfoldr.  Don't know if they are cunning or not, but they were kind of fun.

import Data.List

splitByElem e xs =
    unfoldr f xs
    where f s =
          case break (e ==) s of
            ("",_) -> Nothing
            (a,b) -> Just (a, drop 1 b)


splitByElem1 e xs =
    foldr f [[]] xs
    where f a b = if a == e then [] : b else (a : head b) : (tail b)



J. Garrett Morris wrote:
>
> There is at least one cunning rewriting with foldl, I think, but I
> think this version is clearer.
>
> /g
>
> On 6/12/06, Sara Kenedy <sarakenedy at gmail.com> wrote:
>> Hi all,
>>
>> I want to write a function to separate a string into a list of strings
>> separated by commas.
>>
>> Example:
>> separate :: String -> [String]
>>
>> separate "Haskell, Haskell, and Haskell" = ["Haskell", "Haskell", 
>> "and Haskell"]
>>
>> If anyone has some ideas, please share with me. Thanks.
>>
>> S.
>> _______________________________________________
>> Haskell-Cafe mailing list
>> Haskell-Cafe at haskell.org
>> http://www.haskell.org/mailman/listinfo/haskell-cafe
>>
>
>



More information about the Haskell-Cafe mailing list