15

I'm trying to split a list in Haskell. As to my knowledge, the easiest way to do this is with splitOn, but this function requires Data.List.Split, so I tried to run import Data.List.Split in Prelude. However, I got the following error:

Could not find module Data.List.Split

Simply importing Data.List does work, however.

What could I do to solve this? Or, even better: is there an easy, built-in alternative to split lists?

5
  • What do you want to split the list on? Is it, by any chance, a String you want to split on '\n' or \s+? Commented Dec 9, 2015 at 9:45
  • I'm sorry, I should have been clearer. I would like to split a String on whitespaces. Commented Dec 9, 2015 at 10:11
  • You do know about cabal or stack, right? — BTW, it's also quite easy to split lists with tools from base only... Commented Dec 9, 2015 at 10:52
  • @Algorithm_NL: Then this is a XY problem. You were actually trying to split a string, but asked about your (non-working) solution. Commented Dec 9, 2015 at 12:08
  • @Zeta Wow, I didn't realize that. Thanks for the clarification! Commented Dec 9, 2015 at 13:23

2 Answers 2

14

Data.List.Split is not in the base I think you'll have to install split

Update

after the clarification in the comments that only splitting on whitespace is required - use words/lines to your need - see also @Zeta's answer.

Sign up to request clarification or add additional context in comments.

6 Comments

Good to know, thanks. Would there be any way to do this without installing packages?
but I think it is in the haskell plattform - since ghc-7.8, and even though it is not "safe" for small projects using ghc-7.6 I just copy paste the code in some module to not depend on the whole split package
if you add a split == 0.2.2 to your build-depends:-statements it is quite simple to install the package - why would you like to avoid it?
@epsilonhalbe: Maybe he doesn't even use a .cabal or .yaml file and only wants to write a stand-alone Haskell script for runhaskell.
sometimes I don't think about the obvious use-cases
|
8

To split a String on arbitrary white space (e.g. any Char c where Data.Char.isSpace c is True), use words:

-- words :: String -> [String]
ghci> words "Hello World, I'm a string \n example   \r\t with white space"
["Hello","World,","I'm","a","string","example","with","white","space"]

No need for additional imports, since words is part of the Prelude.

2 Comments

How do you split on a given string that is not necessarily whitespace? For example when reading a csv file.
@user3224967 CSV is a lot more complicate than that, since " breaks delimiter, e.g. Mayer;John;"Department of StackOverflow; Washington" is a record with three, not four fields.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.