Home > Blockchain >  How to split list without losing the head of the list
How to split list without losing the head of the list

Time:08-22

I'm trying to create a function that takes a list and returns two lists by splitting the list in half. Right now I have it so it splits the list in half like I want, but the head of the list is removed.

halve       :: [a] -> ([a],[a])
halve []    = ([],[])
halve [x]   = ([x],[])
halve (x:xs) =  (splitAt half xs)
    where len = length xs
          half = len `div` 2

If I call the function with halve [1,2,3,4] the output is ([2],[3,4]) I would like the output to include x like ([1,2],[3,4])

Is there a way to do this?

CodePudding user response:

You use a reference to the entir elist, so:

halve :: [a] -> ([a],[a])
halve []  = ([],[])
halve [x] = ([x],[])
halve xs  = splitAt half xs
  where half = length xs `div` 2

Your program will however run for endlessly for an infinite amount of time. You should look for a recursive method to tackle this.

The second line with halve [x] = ([x], []) also seems counter-intuitive, since for halve [1,4,2], it will split as ([1], [4,2]) and thus your splitAt currently favors putting an element in the second item of the 2-tuple.

  • Related