Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I'm getting "Exception: Prelude.head: empty list"?

Can't figure out why the pattern matching isn't working! I'm beginning with Hasklell, so be patient!

-- matrix implemented as a list of lists (rows of the matrix)
test_matrix3 = [[1,0,0],[2,-3,0],[4,5,6]]

-- transpose of a given matrix
transpose    (x:[]) = [x]
transpose all@(x:_) = map head all : transpose ([tail y | y <- all])

Executing:

*Main> transpose test_matrix3
[[1,2,4],[0,-3,5],[0,0,6],[*** Exception: Prelude.head: empty list
like image 438
gremo Avatar asked Mar 05 '26 16:03

gremo


2 Answers

  transpose [[1,0,0],[2,-3,0],[4,5,6]]
= [1,2,4] : transpose [[0,0],[-3,0],[5,6]]
= [1,2,4] : [0,-3,5] : transpose [[0],[0],[6]]
= [1,2,4] : [0,-3,5] : [0,0,0] : transpose [[],[],[]]

And here is where it happens. This does not match the first pattern, because it is not a singleton list -- it is a list with three elements. So:

= [1,2,3] : [0,-3,5] : [0,0,0] : map head [[],[],[]] : transpose (map tail [[],[],[]])

Which will give you one error for each empty list, since neither head nor tail are defined on empty lists.

like image 92
luqui Avatar answered Mar 08 '26 06:03

luqui


This one worked for me:

transpose' ([]:_) = []
transpose' xs = (map head xs) : (transpose' (map tail xs))

Test:

*Main> transpose' test_matrix3
[[1,2,4],[0,-3,5],[0,0,6]]
like image 37
YasirA Avatar answered Mar 08 '26 04:03

YasirA