Understanding pattern matching and activity patterns in F #

Source: Internet
Author: User

Pattern matching, which allows us to perform different operations based on the different identifier values, is often compared to the if...else or switch syntax structure in C #, and the conclusion is often that pattern matching is more flexible and powerful than the Matching. Let's first analyze where it is flexible and powerful.

Why is pattern matching flexible and powerful?

In some of the essays I wrote earlier, there were several references to pattern matching, such as the ability to match simple values (integers, strings), or to. NET type to match, look at the following two simple examples:

F# Code - 对简单值和.NET类型进行匹配
// 对简单值进行匹配。
let rec fibonacci x =
  match x with
  | x when x <= 0 -> failwith "x必须是正整数。"
  | 1 -> 1
  | 2 -> 1
  | x -> fibonacci(x - 1) + fibonacci(x - 2)

printfn "%i" (fibonacci 2) // -> 1
printfn "%i" (fibonacci 4) // -> 3
// 对.NET类型进行匹配。
open System
let typeToString x =
  match box x with
  | :? Int32 -> "Int32"
  | :? Double -> "Double"
  | :? String -> "String"
  | _ -> "Other Type"

As you can see, the pattern matches used here are not too much of a surprise and can be converted to if...else or switch structures without much effort.

Don't rush away, the list is a typical data structure in FP, and we apply pattern matching to it.

F# Code - 对列表应用模式匹配
// 对列表应用模式匹配。
let listOfList = [[2; 3; 5]; [7; 11; 13]; [17; 19; 23; 29]]
let rec concatenateList list =
  match list with
  | head :: tail -> head @ (concatenateList tail)
  | [] -> []

let rec concatenateList2 list =
  if List.nonempty list then
    let head = List.hd list in
    let tail = List.tl list in
    head @ (concatenateList2 tail)
  else
    []

let primes = concatenateList listOfList
print_any primes // [2; 3; 5; 7; 11; 13; 17; 19; 23; 29]

Listoflist is a list of lists, two functions concatenatelist and concatenateList2 are all connected to a large list of listoflist elements, only one is implemented in pattern matching, one using If...then ... else structure implementation. You can see that Concatenatelist's code is more concise, but is it just so? In ConcatenateList2, we do this by taking out one of the nodes in the traditional way that the list in F # is implemented in a chain table, which is more specific and detailed; and in Concatenatelist we pass two simple patterns "Head:: Tail" and "[]" cover all the possibilities of the list, so we find a way to better decompose the data structure of the list so that we can work with the list more generally.

Similarly, let's look at the union type. A union type, sometimes called a sum type or discriminated union, that combines a set of data with different meanings or structures. A typical application of it is to represent a tree:

F# Code - 对Union类型应用模式匹配
type BinaryTree<'a> =
  | Leaf of 'a
  | Node of BinaryTree<'a> * BinaryTree<'a>

let rec printBinaryTreeValues t =
  match t with
  | Leaf x -> printfn "%i" x
  | Node (l, r) ->
    printBinaryTreeValues l
    printBinaryTreeValues r

printBinaryTreeValues (Node ((Node (Leaf 1, Leaf 2)), (Node (Leaf 3, Leaf 4))))

This defines a generic binary tree type by binarytree< ' a>, where the Printbinarytreevalues function is used to print the value of its node, which needs to determine the type of node (subtree or leaf), and interestingly, the leaf and node are automatically abstracted as " Mode ", does not require any extra work. So you can see some of the so-called "flexible, powerful" shadow, for the union type of data structure, pattern matching can be very simple, natural decomposition, processing it.

In addition to the list and union types, tuples are similar to pattern matching "adaptive", which is enough to solve a lot of problems. So what's the big trick in F # for other more complex scenarios or more specific areas? You can definitely get it, this is the mode of activity.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.