Haskell pattern matching - what is it?

前端 未结 5 684
慢半拍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:59

    Pattern matching is, at least in Haskell, deeply tied to the concept of algebraic data types. When you declare a data type like this:

    data SomeData = Foo Int Int
                  | Bar String
                  | Baz
    

    ...it defines Foo, Bar, and Baz as constructors--not to be confused with "constructors" in OOP--that construct a SomeData value out of other values.

    Pattern matching is nothing more than doing this in reverse--a pattern would "deconstruct" a SomeData value into its constituent pieces (in fact, I believe that pattern matching is the only way to extract values in Haskell).

    When there are multiple constructors for a type, you write multiple versions of a function for each pattern, with the correct one being selected depending on which constructor was used (assuming you've written patterns to match all possible constructions--which it's generally good practice to do).

提交回复
热议问题