簡體   English   中英

如何將復雜表達式傳遞給參數化的活動模式?

[英]How can I pass complex expression to parametrized active pattern?

我將活動模式“表達式”定義如下:

let (|Expression|_|) expression _ = Some(expression)

現在我正在嘗試以這種方式使用它:

match () with
| Expression((totalWidth - wLeft - wRight) / (float model.Columns.Count - 0.5)) cw
    when cw <= wLeft * 4. && cw <= wRight * 4. ->
        cw
| Expression((totalWidth - wLeft) / (float model.Columns.Count - .25)) cw
    when cw <= wLeft * 4. && cw > wRight * 4. ->
        cw
| Expression((totalWidth - wRight) / (float model.Columns.Count - .25)) cw
    when cw > wLeft * 4. && cw <= wRight * 4. ->
        cw
| Expression(totalWidth / float model.Columns.Count) cw
    when cw > wLeft * 4. && cw > wRight * 4. ->
        cw
| _ -> System.InvalidProgramException() |> raise

但這會導致“錯誤 FS0010:模式中出現意外符號 '-'”。 那可以修嗎?

我想要做的是清楚地寫出以下方程的解:

max(wl - cw *.25, 0) + max(wr - cw *.25) + cw * columnCount = ActualWidth

其中 cw 是唯一的變量。

你能提出更好的方法嗎?

可用作參數化活動模式的 arguments 的表達式語言在某些方面受到限制。 據我所知, F# 規范沒有明確說明,但語法表明必須可以將參數表達式解析為pat-param (第 90 頁):

拍參數:=
| 常量
| 長期認同
| [拍參數; ... ; 拍參數]
| 拍參數,...,拍參數
| 長標識pat-param
| pat-param :類型
| <@ expr @>
| <@@表達式@@>
| null

因此,我認為您需要以不同的方式編寫模式匹配。 您可以將表達式轉換為match構造的普通 arguments 並編寫如下內容:

match 
  (totalWidth - wLeft - wRight) / (float model.Columns.Count - 0.5),
  (totalWidth - wLeft) / (float model.Columns.Count - .25),
  (totalWidth - wRight) / (float model.Columns.Count - .25)
with
| cw1, _, _ when cw1 <= wLeft * 4. && cw1 <= wRight * 4. -> cw1
| _, cw2, _ when cw2 <= wLeft * 4. && cw2 > wRight * 4. -> cw2
| _, _, cw3 when cw3 > wLeft * 4. && cw3 <= wRight * 4. -> cw3
| _ -> totalWidth / float model.Columns.Count

如果表達式中使用的模式始終相同,您還可以使用活動模式,例如:

let (|Calculate|) w p _ =
  (totalWidth - w) / (float model.Columns.Count - p)

...然后寫下類似的東西:

let wDif = wLeft - wRight
match () with
| Calculate wDif 0.5 cw -> cw
| Calculate wLeft 0.25 cw -> cw
// .. etc.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM