Map.tryFind返回null而不是None

时间:2014-01-21 18:43:19

标签: cookies f#

我有以下脚本。

type SetCookie = {
    NameValue : string * string;
    Domain : string option;
    Path : string option;
    Expires : string option;
    MaxAge : string option;
    Secure : bool; // ? no associated value, anything better than bool
    HttpOnly : bool; // ? no associated value, anything better than bool
    }

let GetCookie str =
    let allkeyvalues =
        str.Split ';'
        |> Array.map (fun str ->
            match str.Split '=' with
            | [| key |] -> (key.Trim(), "")
            | [| key; value |] -> (key.Trim(), value)
            | _ -> failwith "there's more than one '='; the format is incorrect.")
    let namevalue = allkeyvalues.[0]
    let attributes =
        Seq.skip 1 allkeyvalues
        |> Seq.map (fun (key, value) ->
            (key.ToLower(), value)) // attribute names are case-insensitive
        |> Map.ofSeq
    {
        NameValue = namevalue
        Domain = Map.tryFind "domain" attributes
        Path = Map.tryFind "path" attributes
        Expires = Map.tryFind "expires" attributes
        MaxAge = Map.tryFind "maxage" attributes
        Secure = Map.containsKey "secure" attributes
        HttpOnly = Map.containsKey "httponly" attributes
    }

然而,函数调用

GetCookie "XXX=YYY; path=/" 

DomainExpires ....和所有其他选项类型而不是None返回null。根据文档,如果没有找到它应该返回None? http://msdn.microsoft.com/en-us/library/ee353538.aspx

  {NameValue =
    ("XXX", "YYY");
   Domain = null;
   Path = Some "/";
   Expires = null;
   MaxAge = null;
   Secure = false;
   HttpOnly = false;}

2 个答案:

答案 0 :(得分:7)

F#None值实际上由.NET null表示。在这种情况下,这会以通用方式打印出来,但在其他方面只是一个表示细节。实际上,您可以通过注释一个没有CompilationRepresentationFlags.UseNullAsTrueValue参数的联合案例来为您自己的歧视联盟获取此行为。

答案 1 :(得分:3)

F#规范声明使用None表示null

  

5.4.8无效

     

以null作为表示值的类型。这些类型不允许   null文字但使用null值作为表示。

     

对于这些类型,使用null文字不是直接的   允许的。但是,该类型的一个或所有“正常”值是   由null值表示。以下是这种类型   类别:

     

任何具有此类型的联合类型   Microsoft.FSharp.Core.CompilationRepresentation(CompilationRepresentationFlags.UseNullAsTrueValue)   属性标志和单个空联合情况。空值表示   这个案例。特别地,null表示F#选项中的None< _>   类型。

相关问题