After learning F # Over the past few days, I feel that F # is indeed concise and powerful in many aspects. Its match expression is one of them. Match with is similar to switch of C, however, the functions are much more powerful. The following is an example:
Let print_any x = printfn "% A" x let rec findsequence L = match l with | [A; B; C; D]-> // a, B, c, D is actually only a placeholder symbol, indicating an array of four elements. Of course, if it matches, you can access the four elements printfn "last 4 numbers in the list were % I" a B c d | 1: 2 :: 3: tail-> // such as 1, 2, 3, any element printfn "found sequence 1, 2, 3 within the list" findsequence tail | HEAD: Mid :: tail-> // matches the tuples of the three elements. Because each array contains an empty value at the end, any element larger than 2 can be matched. printfn "XXXX: % % A "head mid tail findsequence tail | HEAD: tail-> // match a binary group with the same name. Printfn "XXXX: % A" head tail | []-> () Let testsequence = [1; 2; 3; 4; 5; 6; 7; 8; 9; 8; 7; 6; 5; 4; 3; 2; 1] Let b1 = findsequence testsequence print_any B1
Match with is really powerful, especially when the set is used as a branch. however, this is misleading, that is, the head above. Tail is not the header and bit in the linked list we understand. It is actually a placeholder symbol here. of course, this is because of the symbolic name, and the head and tail of the list are misleading:
let listOfList = [[2; 3; 5]; [7; 11; 13]; [17; 19; 23; 29]] let rec concatList l = match l with | head :: tail -> head @ (concatList tail) | [] -> [] let rec concatListOrg l = if List.isEmpty l = false then let head = List.head l in let tail = List.tail l in head @ (concatListOrg tail) else [] let print_any x = printfn "%A" x let primes = concatList listOfList print_any primes
Head points to the sequence Header element, while tail points to the remaining sequence except the head element. of course, there is no right or wrong, but it is easy to misunderstand. when we are learning the linked list, head and tail generally refer to the first and last elements. it is also difficult to express the meaning of tail with the remaining remain. of course it doesn't matter if you understand it.