Pattern matching of nested list in Haskell
I want to use nested lists of nestedness 2 to represent matrix (e.g. [[1,2,3],[4,5,6]]
). How would I define a function that process small submatrices (say 2*2)? I expected something like this:
f (a1:a2:a) 开发者_高级运维: (b1:b2:b) : x = ...
Where a1, a2 are two consecutive elements of first row and b1, b2 — second row. a, b are rests of first and second row correspondigly. x is the rest of matrix rows.
But this clearly doesn't work.
Thanks in advance!
I expected something like this:
f (a1:a2:a) : (b1:b2:b) : x = ...
You've got the right idea. All you're missing is a pair of parentheses:
f ((a1:a2:a) : (b1:b2:b) : x) = ...
Don't forget you can just use a bit of where
syntax
f xs = ...
where (a1:a2:a) = head xs
(b1:b2:b) = head (tail xs)
x = tail (tail xs)
It's worth noting, however, that pattern matching gives you the benefit of falling down to the next definition of the function if the pattern doesn't match. It would take more guards and stuff to make this where
version do that.
精彩评论