开发者

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

开发者 https://www.devze.com 2023-02-08 01:24 出处:网络
Can\'t figure out why the pattern matching isn\'t working! I\'m beginning with Hasklell, so be patient!

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 hea开发者_运维百科d 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


  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.


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]]


Consider that you are working on a list-of-lists. Therefore your first pattern match always fails on your test matrix. Basically you keep taking the tail of every element of your list, but this doesn't reduce the number of elements in your list, it just reduces their individual size.

To correct this, you may want to modify your first pattern to match on the structure of x.

Remember, list-of-lists!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号