Sunday, 5 June 2016

Haskell: Split lines whenever you see a digit


SplitLines.hs
import System.Environment

splitLines :: String -> [String]
splitLines str =
    let 
        (prefix, suffix) = break isDigit str
    in
        prefix : case suffix of
                    ('0' : rest) -> splitLines rest
                    ('1' : rest) -> splitLines rest
                    ('2' : rest) -> splitLines rest
                    ('3' : rest) -> splitLines rest
                    ('4' : rest) -> splitLines rest
                    ('5' : rest) -> splitLines rest
                    ('6' : rest) -> splitLines rest
                    ('7' : rest) -> splitLines rest
                    ('8' : rest) -> splitLines rest
                    ('9' : rest) -> splitLines rest
                    _ -> []

isDigit :: Char -> Bool
isDigit num = (num == '0' || num == '1' || num == '2' || num == '3' || num == '4' || 
               num == '5' || num == '6' || num == '7' || num == '8' || num == '9')

*Main> :load SplitLines.hs
[1 of 1] Compiling Main             ( SplitLines.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> splitLines "Hello 123 How are you 324 bcd"
["Hello ","",""," How are you ","",""," bcd"]
*Main> 
*Main> splitLines "a1b2c3d4e5f6g7h8j9k10"
["a","b","c","d","e","f","g","h","j","k","",""]



Previous                                                 Next                                                 Home

No comments:

Post a Comment