Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching of nested list in Haskell

Tags:

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!

like image 481
Artem Pelenitsyn Avatar asked Jan 29 '11 21:01

Artem Pelenitsyn


2 Answers

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) = ...
like image 109
sepp2k Avatar answered Nov 08 '22 18:11

sepp2k


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.

like image 2
Dan Burton Avatar answered Nov 08 '22 18:11

Dan Burton