Skip to content

NullReferenceException when type annotation is not used #1553

@hvester

Description

@hvester

System.NullReferenceException is thrown from presumably valid function. When the argument of the function is annotated with the same type that was the inferred type the problem does not reproduce.

Repro steps

The issue can be reproduced with the code below.

let weightedMedian (weightedList : (float<'u> * float<'v>) list) =
    let sumOfWeights = List.sumBy fst weightedList

    if sumOfWeights <= 0.0<_> then
        invalidArg "weightedList" "Sum of weights must be positive"

    let rec loop accumululatedWeight (remaining : (float<'u> * float<'v>) list) =
        match remaining with
        | [] -> failwith "Input list to weightedMedian must not be empty!"
        | (weight, value) :: _ when accumululatedWeight + weight >= 0.5 * sumOfWeights ->
            value
        | (weight, _) :: tail ->
            loop (accumululatedWeight + weight) tail

    loop 0.0<_> (List.sortBy snd weightedList)


let weightedMedian2 weightedList =
    let sumOfWeights = List.sumBy fst weightedList

    if sumOfWeights <= 0.0<_> then
        invalidArg "weightedList" "Sum of weights must be positive"

    let rec loop accumululatedWeight (remaining : (float<'u> * float<'v>) list) =
        match remaining with
        | [] -> failwith "Input list to weightedMedian must not be empty!"
        | (weight, value) :: _ when accumululatedWeight + weight >= 0.5 * sumOfWeights ->
            value
        | (weight, _) :: tail ->
            loop (accumululatedWeight + weight) tail

    loop 0.0<_> (List.sortBy snd weightedList)


weightedMedian [ (0.3, 1.0); (0.3, 2.0); (0.4, 3.0) ] // Returns 2.0 as expected
weightedMedian2 [ (0.3, 1.0); (0.3, 2.0); (0.4, 3.0) ] // Throws System.NullReferenceException: Object reference not set to an instance of an object.

Expected behavior

weightedMedian and weightedMedian2 should behave identically.

Actual behavior

weightedMedian works as expected while weightedMedian2 always throws System.NullReferenceException.

Related information

  • Operating system: Windows 7
  • .NET Framework 4.5
  • F# Interactive version 14.0.23413.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugImpact-Medium(Internal MS Team use only) Describes an issue with moderate impact on existing code.

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions