2011-05-29 18 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