Non-exhaustive patterns error with arrays in Haskell

0

How are you? I am doing some exercises with Haskell and when compiling the program I get an error as if I were missing a pattern in "cab". I really do not know what it can be. I spent the whole afternoon looking for the error but I can not find it. Exercise basically back a matrix "[[2,8,14], [3,9,15], [4,10,16]]" a "[[2,3,4], [8,9,10], [14,15,16]]"

I attach the code

cab :: [Int] -> Int
cab (x:y) = x

todasLasCabezas :: [[Int]] -> [Int]
todasLasCabezas [] = []
todasLasCabezas (x:y) = cab(x) : todasLasCabezas(y)


todasLasColas :: [[Int]] -> [[Int]]
todasLasColas [] = []
todasLasColas ((u:v):z) = v : todasLasColas(z)


darVueltaLista :: [[Int]] -> [[Int]]
darVueltaLista [] = []
darVueltaLista (x:y) = todasLasCabezas(x:y) : darVueltaLista(todasLasColas(x:y))

main = do
print (darVueltaLista([[2,8,14],[3,9,15],[4,10,16]]))
    
asked by Fcr 28.10.2018 в 00:53
source

1 answer

0

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.

    
answered by 28.10.2018 в 03:25