开发者

Why does this f# function expects an integer[] instead of byte array

Could someone please show me why the function below expects integer[] instead of byte[]

type Node =
    | InternalNode of int*Node*Node
    | LeafNode of int * byte

let weight node =
    match node with 
    |InternalNode(w,_,_) -> w
    |LeafNode(w,_)-> w

let createNodes inputValues =
    let getCounts (leafNodes:(int*byte)[])= 
   开发者_如何学Python     inputValues |>Array.iter
            (fun b-> let (w,v) =leafNodes.[(int)b]
                     leafNodes.[(int)b]<-(w+1,v))

        leafNodes
    [|for b in 0uy..255uy -> (0 ,b)|] |>getCounts
    |>List.ofArray
    |>List.map LeafNode


The only place that tells the F# compiler something about the type of the parameter is inside the lambda function given to Array.iter (from the use of this higher-order function, the compiler infers that you're working with arrays). Inside the lambda function you have:

leafNodes.[(int)b] 

As a side-note, int in this code is just a normal F# function (not a special type cast construct), so the usual way to write it would be just:

leafNodes.[int b] 

Now, the compiler knows that b (that is, values of the array given as the argument) can be converted to integer, however the int function works with other types (you can write for example int 3.13f. In ambiguous cases like this, the compiler uses int as the default type, so that's the reason why you're seeing a type int[].

You can add type annotations to the declaration like this (and it will work without any other changes, because byte can be converted to integer using the int function):

let createNodes (inputValues:byte[]) =  
  // ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜