How to split a string with two conditions

Asked

Viewed 220 times

0

Basically, from the string "222 2333 33", I wanted to split into several strings, when you find an empty space or a different number next to you.

For example, in the string above I wanted it to be ["222","2","333","33"].

The code I made is below, only in my case I can only divide when it finds the empty space. Missing when the numbers are different.

sliceIt :: String -> [String]

sliceIt xs = words xs

And it would be possible to do this problem with recursion?

  • You cannot use a ready-made function? split

  • Can I, but in this case how would I use it? Because I want it to split whenever it finds empty space or a different number

  • 1

    I did what I could to improve the editing, but please: DO NOT USE IMAGE, enter the code

  • I won’t know how to answer because I don’t know anything from Haskell, but a suggestion is you go through the string, when meeting a different guy from the previous one, add a blank (" ") and then use the split..

1 answer

0

If you want to define your own version, here is a recursive alternative using the function span

sliceIt :: String -> [String]
sliceIt [] = []
sliceIt (' ':xs) = sliceIt xs
sliceIt (x:xs) = let (a, b) = span (==x) (x:xs) 
               in a:(sliceIt b)

span is a function that receives a predicate p and a list l and which returns a single l with the elements that satisfy the predicate p and where the second element of the Tuplo are the other elements of l. span p l is equivalent to (takeWhile p l, dropWhile p l) therefore the previous version can be considered equivalent to:

sliceIt :: String -> [String]
sliceIt [] = []
sliceIt (' ':xs) = sliceIt xs
sliceIt (x:xs) = (x : (takeWhile (== x) xs)) : (sliceIt $ dropWhile (== x) xs)

Here is yet another alternative using only predefined functions in the Prelude and List modules

import Data.List

sliceIt :: String -> [String]
sliceIt = concatMap group . words 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.