Home > OS >  Haskell - Problem with non-exhaustive patterns in function
Haskell - Problem with non-exhaustive patterns in function

Time:10-12

I have the following haskell code:

f :: [[(a,[b])]] -> Int
f ([_]:[(x,[xs])]:[y,ys]:[]) = 1

x1 ::[[(Int,[Int])]]
x1 = [[(1,[1,2])],[(1,[1,2])],[(1,[1,2]),(1,[1,2])],[]]

Why doesn't x1's pattern matching to function f?

CodePudding user response:

It's pretty hard to read as-is. Let's use some creative whitespace to line things up.

f   ( [_        ]:[(x,[xs ])]:[y        ,ys       ]   :[]) = 1
x1 = [[(1,[1,2])],[(1,[1,2])],[(1,[1,2]),(1,[1,2])],[]]

Okay. So there's actually a couple different things that aren't going as you expect!

  • [xs] does not match [1, 2], because [xs] is a one-element list and [1, 2] is a two-element list (possible fix: xs instead of [xs])
  • [y, ys] happens to match, but I suspect not in the way you intended: y matches to the first element of the list, just as I think you intend, but ys to the second element of the list, not the remainder of the list I think you intend (possible fix: (y:ys) instead of [y, ys])
  • your pattern's :[] matches the closing bracket of a list definition, not a final [] element (possible fix: :[]:[] instead of :[]; the first [] there matches the element, and the second [] matches the end-of-list marker)
  • Related