F # Adventure Tours (II): Functional Programming (II.)

Source: Internet
Author: User

Mode matching (pattern Matching)

Pattern matching allows you to perform different operations based on the different identifier values. It's a bit like a bunch of if...else structures, like the switch in C + + and C #, but it's more powerful and flexible.

Looking at the Lucas sequence example, the Lucas sequence is defined just like the Fibonacci sequence, except that the starting values are different:

Code
let rec luc x =
  match x with
  | x when x <= 0 -> failwith "value must be greater than zero"
  | 1 -> 1
  | 2 -> 3
  | x -> luc(x - 1) + luc(x - 2)

printfn "(luc 2) = %i" (luc 2)
printfn "(luc 6) = %i" (luc 6)

Here you can see the simple application of pattern matching, using the keyword match and with, the different pattern rules between the "|" Separated, and "->" indicates what the result of the operation would be if the pattern was matched.

This example prints the result:

Output
(luc 2) = 3
(luc 6) = 18

Match rules in the order they are defined, and pattern matching must be fully defined, that is, there is at least one pattern for any possible input value (that is, it can be handled); otherwise the compiler will report an error message. In addition, the preceding rules should not be more "general" than the latter, otherwise, the following rule will never be matched, and the compiler will report a warning message, much like the exception handling in C #, when we catch an exception, we can't first "exception" the exception, and then catch the "more specific" The NullReferenceException exception.

You can add a when guard statement (guard) to a pattern rule to interpret the When statement as a stronger constraint on the current rule, which matches only when the value of the When statement is true. In the first rule of the example, if there is no when statement, then any integer can match the pattern, and when the statement is added, only a positive integer can be matched. For the simplest case, we can omit the first "|" :

Code
let boolToString x =
  match x with false -> "False" | _ -> "True"

This example contains two pattern rules, "_" can match any value, so when the X value is false match the first rule, otherwise the second rule is matched.

Another useful feature is that we can combine two pattern rules and treat them the same way, as in the case of a switch...case structure in C # that can be merged into two.

Code
let stringToBool x =
  match x with
  | "T" | "True" | "true" -> true
  | "F" | "False" | "false" -> false
  | _ -> failwith "Invalid input."

In this case, we combine the three pattern rules to convert the string value to the corresponding Boolean value.

You can do pattern matching for most of the types defined in F #, and the following example shows the matching of tuples.

Code
let myOr b1 b2 =
  match b1, b2 with
  | true, _ -> true
  | _, true -> true
  | _ -> false

let myAnd p =
  match p with
  | true, true -> true
  | _ -> false

These two functions illustrate how to apply pattern matching to tuples, whose function is to find the results of two Boolean or and and and operations. In Myor, the first to second two pattern rules can know that B1, B2, if one is true, evaluates to true, or false. The result of Myor true false is True,myand (true, false) and the result is false.

A common use of pattern matching is to match a list, in fact, for a list, the pattern matches better than the if...then...else structure. Look at the following example:

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

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 code that uses pattern matching is more concise and straightforward. Observe the Concatenatelist function, which processes the list by first removing the header element (head) of the list, processing it, and then recursively processing the remaining elements, which is actually the most common way (but not the only way) to handle the list through pattern matching.

In F #, pattern matching can also be used elsewhere, as will be described in subsequent articles.

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.