鑑於以下有效模式: let (| HasMatch |) (x:string) =
if x.Contains("0") then Some()
else None;;
而下面的模式匹配FUNC: let testFn x = function
| HasMatch i -> printfn "%A" i
| _ -> printf "nope";;
我發現通過基因Belitski的優秀圖書F# Design Patterns驗證碼: let (| `` I'm active pattern `` |) x = x + 2
let (`` I'm active pattern `` y) = 40
(*
val (|`` I'm active pattern ``|) : x:int -> int
val y : int = 42
*
我如下定義在F#表達式目錄樹結構: type Num = int
type Name = string
type Expr =
| Con of Num
| Var of Name
| Add of Expr * Expr
| Sub of Expr * Expr
| Mult of Expr * Expr
| Div of Expr
由於我只找到關於這個錯誤的日文網頁,我想,讓我們記錄下來,問這裏,因爲我的日語有點生疏。 如果我有以下FSharp有源圖案(簡化的示例): let (|InRange|OutOfRange|) from too =
function
| input when input >= from && input <= too -> InRange
| _ -> OutOfRa
我解析了FSharp中的代碼引用,並構建了模式助手。所有進行得很順利,直到我試圖 let (|BinaryFn|_|) fn (input:Expr) =
function
| SpecificCall fn (_,_,l::r::[]) -> Some(l,r)
| _ -> None
let (|Multiply|_|) x =
function
// Standard pattern matching.
let Foo x =
match x with
| 1 ->
// ... lots of code, only evaluated if x == 1
| 2 ->
// ... lots of code, only evaluated if x == 2
// Standa
當談到F#的許多領域時,我仍然是一個新手。我更多地出於好奇而提出這個問題,而不是出於實際的業務需要。是否有任何方法可以匹配列表中的第一個n項目,而不管它們出現的順序是什麼?爲了澄清,請看下面的例子: type MyEnum =
| Foo of int
| Bar of float
| Baz of string
let list = [ Foo 1 ; Bar 1
讓我們有幾種類型的二進制節點,其他類型的節點之間的樹的類型定義,即 type Tree =
| BinaryNodeA of Tree * Tree
| BinaryNodeB of Tree * Tree
| [Other stuff...]
我要操縱這棵樹使用遞歸函數,例如,可以交換任何類型的二進制節點的子節點(通過構建新節點)。引起我瘋狂的問題是:如何匹配所有BinaryNode,
我注意到我不能使用相同的選項創建兩個活動模式,但我可以有兩個類似的人沒有任何警告:匹配這樣 let (|A|B|C|) c =
if (c = 'a') then A
else if (c = 'b') then B
else C
let (|A|B|D|) c =
if (c = '1') then A
else if (c = '2') t