Haskell (n+1) in pattern matching

前端 未结 1 1171
我在风中等你
我在风中等你 2021-01-07 18:47

I was doing the 99 Problems in Haskell when I encountered a solution to Problem 19 that I did not fully understand.

The task is to write a rotate function that works

相关标签:
1条回答
  • 2021-01-07 19:29

    It's a specific case of what is called "n+k patterns", which is generally disliked, and will be has been removed from the language. See here for more information.

    Here is a good note on n+k patterns, which quotes the following from the Haskell 98 Report (emphasis mine):

    Matching an n+k pattern (where n is a variable and k is a positive integer literal) against a value v succeeds if x >= k, resulting in the binding of n to x - k, and fails otherwise. Again, the functions >= and - are overloaded, depending on the type of the pattern. The match diverges if the comparison diverges.

    The interpretation of the literal k is the same as in numeric literal patterns, except that only integer literals are allowed.

    So the n+1 is only matched if n is at least 1, as you suspected. Your alternative code removes this restriction, resulting in overlapping pattern matches.

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