Haskell pattern matching - what is it?

前端 未结 5 641
慢半拍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 03:02

    In a functional language, pattern matching involves checking an argument against different forms. A simple example involves recursively defined operations on lists. I will use OCaml to explain pattern matching since it's my functional language of choice, but the concepts are the same in F# and Haskell, AFAIK.

    Here is the definition of a function to compute the length of a list lst. In OCaml, an ``a listis defined recursively as the empty list[], or the structureh::t, wherehis an element of typea(abeing any type we want, such as an integer or even another list),tis a list (hence the recursive definition), and::` is the cons operator, which creates a new list out of an element and a list.

    So the function would look like this:

    let rec len lst =
      match lst with
        [] -> 0
      | h :: t -> 1 + len t
    

    rec is a modifier that tells OCaml that a function will call itself recursively. Don't worry about that part. The match statement is what we're focusing on. OCaml will check lst against the two patterns - empty list, or h :: t - and return a different value based on that. Since we know every list will match one of these patterns, we can rest assured that our function will return safely.

    Note that even though these two patterns will take care of all lists, you aren't limited to them. A pattern like h1 :: h2 :: t (matching all lists of length 2 or more) is also valid.

    Of course, the use of patterns isn't restricted to recursively defined data structures, or recursive functions. Here is a (contrived) function to tell you whether a number is 1 or 2:

    let is_one_or_two num =
      match num with
        1 -> true
      | 2 -> true
      | _ -> false
    

    In this case, the forms of our pattern are the numbers themselves. _ is a special catch-all used as a default case, in case none of the above patterns match.

提交回复
热议问题