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

What's wrong with my guard-based haskell code for halving a list?

Here is the code:

    listhalve :: [a] -> ([a],[a])
listhalve (x:xs)
    | length [x] == length xs = ([x],xs)
    | length [x] <  length xs = listhalve ([x] ++ head xs : tail xs)
    | length [x] > length xs = ([x],xs)

There are no error messages when I run or compile it, it just runs forever in the case of non-pair lists.

I’m aware of different ways to write this function that work. I just want to know what’s wrong with this code specifically.

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 :

Consider that listhalve ([x] ++ head xs : tail xs) is the same as listhalve ([x] ++ xs) which is the same as listhalve (x:xs) which is what you went in with, so endless recursion results.

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