Non-exhaustive patterns in Haskell function

后端 未结 2 1162
谎友^
谎友^ 2021-01-21 14:08

I have a problem with a haskell program. I want to do something like this:

main = do
    print $ map foo [(1, [(2, 3), (4,5)])]

foo :: (Int, [(Int, Int)]) ->         


        
相关标签:
2条回答
  • 2021-01-21 14:20

    It is not an error, it is a warning, telling you that there are some cases in which none of your patterns in foo will apply. If no pattern is matched, the programme will quit with an error, therefore it gives you this warning.

    You may choose to ignore this warning if you're 100% sure that this pattern is always matched. Your match in foo will fail if the second part of the pair contains != 1 list elements. I am quite sure you meant to do something like this:

    foo (a, l) = (a+1, l)
    

    To copy the given list.

    0 讨论(0)
  • 2021-01-21 14:26

    (a, [(b, c)]) does not match (1, [(2, 3), (4, 5)]), because the list in the latter has two elements while your pattern requires there to be only one.

    If you want to leave the list unchanged, use this pattern instead:

    foo (a, bar) = (a+1, bar)
    

    Now bar will match [(2, 3), (4, 5)] because it is just a binding which will match anything of the correct type.

    0 讨论(0)
提交回复
热议问题