I was reviewing your code and saw that you have some errors and not exactly with your function cab
, first you need a stop condition for your recursion in the method allLasCabezas , I solved it in this way:
todasLasCabezas (x:y) = if length y == 0 then [cab(x)] else cab(x) : todasLasCabezas(y)
If you notice when we reach the end of the list y
that the queue will be empty, so compare if its length is 0, in that case I only do [cab(x)]
(the brackets is to convert it to type [Int] which is what the method returns), otherwise I get the header and add the following: cab(x) : todasLasCabezas(y)
.
For allColas it is necessary to do the same, verify that z
is not empty, when it is empty we finish the recursion by doing [v]
:
todasLasColas ((u:v):z) = if length z /= 0 then v : todasLasColas(z) else [v]
And the most important part is in your "main" function Give BackList , if you notice in your code the function is sent to call again and again without any hope of stopping, here what I did was compare that x
(head of the list) has a size greater than 1, in that case you can call both functions and repeat the process. Only when its size is smaller we only call allHeads .
Code
cab :: [Int] -> Int
cab (x:y) = x
todasLasCabezas :: [[Int]] -> [Int]
todasLasCabezas (x:y) = if length y == 0 then [cab(x)] else cab(x) : todasLasCabezas(y)
todasLasColas :: [[Int]] -> [[Int]]
todasLasColas ((u:v):z) = if length z /= 0 then v : todasLasColas(z) else [v]
darVueltaLista :: [[Int]] -> [[Int]]
darVueltaLista (x:y) = if length x > 1 then todasLasCabezas(x:y) : darVueltaLista(todasLasColas(x:y)) else [todasLasCabezas(x:y)]
main = do
print (darVueltaLista [[2,8,14],[3,9,15],[4,10,16]])
I recommend reading this Haskell Book has very good topics, I do not know much about Haskell but I hope I have helped you, regards.