How to split a string with two conditions

0

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

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

The code I have written is below, but in my case I can only divide when I find the empty space. Missing when numbers are different.

sliceIt :: String -> [String]

sliceIt xs = words xs

And would it be possible to do this with recursion?

    
asked by anonymous 24.10.2018 / 17:02

1 answer

0

If you want to set your own version, here's a recursive alternative using 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 p fault predicate and a l list and returns a tuple of l with elements that satisfy the p predicate and where the second tuple element is the remaining elements of l . span p l is equivalent to (takeWhile p l, dropWhile p l) where 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's another alternative using only pre-defined functions in the Prelude and List

import Data.List

sliceIt :: String -> [String]
sliceIt = concatMap group . words 
    
05.01.2019 / 11:15