2011-03-17 54 views
0

如何编写一个匹配函数,它需要两个字符串并将它们相互比较?现在我只是有这个。第一个不起作用。有没有更好的办法?如何使用函数参数作为F#中的模式匹配的文字?

let matchFn ([<Literal>]matchString) (aString : string) = match aString with 
                  matchString -> true 
                  | _ -> false 

let matchFn (matchString : string) (aString : string) = match aString with 
                  _ when (matchString = aString) -> true 
                  | _ -> false 

回答

4

在这种特定的情况下,你当然可以只写aString = matchString,但我想你问的是一般情况。文字只允许在模块级别上使用,并且它们的右侧必须有一个简单的常量表达式(source)。

但是,您可以对这种情况使用活动模式。例如(从here):

let (|Equals|_|) expected actual = 
    if actual = expected then Some() else None 

,然后用它是这样的:

let matchFn (matchString : string) (aString : string) = 
    match aString with 
    | Equals matchString -> true 
    | _ -> false 
1

您可以使用把守的比赛:

let matchFn matchString (aString : string) = match aString with 
               x when x = matchString -> true 
               | _ -> false 

或者更地道:

let matchFn (matchString:string) = function 
    | x when x = matchString -> true 
    | _ -> false