Search code examples
listhaskelllist-manipulation

Splitting up inner lists within a list of lists in Haskell


I am currently struggling with a problem to split a current list into two within a list of lists. For example if I have:

[[A,B,C,F],[F,G,H,I]]

Is there any easy way to split the second list (because F is the head) so that you end up with

[[A,B,C,F],[F],[G,H,I]]

I have attempted this in different ways but I cannot find a way to return two separate values from a function. Furthermore since the value I would like to split on is repeated within multiple inner lists I only want to split when it is the head of a list and at no other time. I attempted it like so:

splitList [] = [];
splitList (F:xs) = [[F]] ++ [xs];
splitList x = [x];

However this obviously returned a list of lists within the overall list causing it to in turn not work since I mapped it to every element in the list. Any help would be greatly appreciated as I only recently started working in Haskell.


Solution

  • Functions return one value, but this value may be a list or tuple, for example, and so in that way you can return multiple values.

    First define how to split an 'F' off the head of the list.

    splitF :: String -> [String]
    splitF ('F':xs) = ["F", xs]
    splitF xxs      = [xxs]
    
    splitF "ABCF" ≡ ["ABCF"]
    splitF "FGHI" ≡ ["F","GHI"]
    

    Now map this function on a list.

    map splitF ["ABCF","FGHI"] ≡ [["ABCF"],["F","GHI"]]
    

    Finally concatenate the lists.

    (concat . map splitF) ["ABCF","FGHI"] ≡ ["ABCF","F","GHI"]
    
    concatMap splitF ["ABCF","FGHI"] ≡ ["ABCF","F","GHI"]