Haskell pattern matching - what is it?

前端 未结 5 696
慢半拍i
慢半拍i 2020-12-08 02:28

What is pattern matching in Haskell and how is it related to guarded equations?

I\'ve tried looking for a simple explanation, but I haven\'t found one.

EDIT:

5条回答
  •  旧巷少年郎
    2020-12-08 02:51

    In a nutshell, patterns are like defining piecewise functions in math. You can specify different function bodies for different arguments using patterns. When you call a function, the appropriate body is chosen by comparing the actual arguments with the various argument patterns. Read A Gentle Introduction to Haskell for more information.

    Compare:

    Fibonacci sequence

    with the equivalent Haskell:

    fib 0 = 1
    fib 1 = 1
    fib n | n >= 2 
          = fib (n-1) + fib (n-2)
    

    Note the "n ≥ 2" in the piecewise function becomes a guard in the Haskell version, but the other two conditions are simply patterns. Patterns are conditions that test values and structure, such as x:xs, (x, y, z), or Just x. In a piecewise definition, conditions based on = or relations (basically, the conditions that say something "is" something else) become patterns. Guards allow for more general conditions. We could rewrite fib to use guards:

    fib n | n == 0 = 1
          | n == 1 = 1
          | n >= 2 = fib (n-1) + fib (n-2)
    

提交回复
热议问题