简体   繁体   中英

Pattern matching of nested list in Haskell

I want to use nested lists of nestedness 2 to represent matrix (eg [[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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM