2011-05-29 71 views
2

我定義如下活動模式「表達」:如何將複雜表達式傳遞給參數化活動模式?

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:意外的符號「 - '模式'。這是可以修復的嗎?

什麼是我想要做的是寫清楚瞭解決以下公式:

最大(WL - CW * 1.25,0)+ MAX(WR - CW * 0.25)+ CW *信息columnCount = ActualWidth

其中cw是唯一的變量。

你能提出任何更好的方法嗎?

回答

6

可以用作參數有源圖案參數表達式的的langauge在某些方面受到限制。據我所知道的,F# specification不說明確,但語法表明它必須能夠解析參數表達式pat-param(第90頁):

拍拍PARAM:=
      | const
      | 長的ident
      | [PAT-PARAM; ...; PAT-PARAM]
      | (PAT-PARAM,...,PAT-PARAM
      | 長的ident拍拍PARAM
      | PAT-PARAM
      | < @EXPR @>
      | < @@EXPR @@>
      | null

所以,我認爲你需要寫出不同的模式匹配。你可以把表達式爲match結構的普通參數,寫這樣的事:

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. 
+0

所以是不可能使用複合功能的主動模式的爭論?例如我們不能做'| MyActive(myfuna >> myfunb)x - > ...'我們只能讓'myfun = myfuna >> myfunb ... | MyActive myfun x - > ...' – colinfang 2013-01-24 21:13:51

+0

是的,我認爲這是正確的 - 你不能直接使用任何複雜的表達式。 – 2013-01-25 00:22:42

相關問題