Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to split list without losing the head of the list

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading