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)[])=
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:As a side-note,
intin this code is just a normal F# function (not a special type cast construct), so the usual way to write it would be just:Now, the compiler knows that
b(that is, values of the array given as the argument) can be converted to integer, however theintfunction works with other types (you can write for exampleint 3.13f. In ambiguous cases like this, the compiler usesintas the default type, so that’s the reason why you’re seeing a typeint[].You can add type annotations to the declaration like this (and it will work without any other changes, because
bytecan be converted to integer using theintfunction):