Skip to content

Implementing 'split' in Haskell #27

@niloy

Description

@niloy

String -> String -> [String]

-- skips the first 'count' elements from array and returns the rest
skip count str = snd(splitAt count str)

-- returns the index of first occurance of 'patt' inside 'str', 'acc' is
-- initilized with 0, used internally.
pos str patt acc
  | str == [] = -1
  | take pattLength str == patt = acc
  | otherwise = pos (tail str) patt (acc + 1)
  where pattLength = length patt

-- break the given string 'str' into 'left' and 'right' portions based on the
-- position of 'patt' occuring inside it. 'left' becomes part of the output
-- array, 'right' is recursively fed to 'split'.
split str patt
  | p == -1 = [str]
  | otherwise = left : split right patt
  where p = pos str patt 0
        parts = splitAt p str
        left = fst parts
        right = skip (length patt) (snd parts)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions