Skip to content

Commit

Permalink
#2451 throw exception when sequence is empty
Browse files Browse the repository at this point in the history
  • Loading branch information
Michał Niegrzybowski authored and alfonsogarciacaro committed May 26, 2021
1 parent 18447c3 commit 0633c4c
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/fable-library/Seq.fs
Original file line number Diff line number Diff line change
Expand Up @@ -807,13 +807,17 @@ let average (xs: seq<'T>) ([<Inject>] averager: IGenericAverager<'T>): 'T =
let mutable count = 0
let folder acc x = count <- count + 1; averager.Add(acc, x)
let total = fold folder (averager.GetZero()) xs
averager.DivideByInt(total, count)
if count = 0 then
invalidArg "xs" LanguagePrimitives.ErrorStrings.InputSequenceEmptyString
else averager.DivideByInt(total, count)

let averageBy (f: 'T -> 'U) (xs: seq<'T>) ([<Inject>] averager: IGenericAverager<'U>): 'U =
let mutable count = 0
let inline folder acc x = count <- count + 1; averager.Add(acc, f x)
let total = fold folder (averager.GetZero()) xs
averager.DivideByInt(total, count)
if count = 0 then
invalidArg "xs" LanguagePrimitives.ErrorStrings.InputSequenceEmptyString
else averager.DivideByInt(total, count)

let permute f (xs: seq<'T>) =
delay (fun () ->
Expand Down
8 changes: 8 additions & 0 deletions tests/Main/SeqTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,14 @@ let tests =
sumFirstTwo zs
|> equal 1.

testCase "Seq.average for empty sequence" <| fun () ->
let xs = Seq.empty<float>
(try Seq.average xs |> ignore; false with | _ -> true) |> equal true

testCase "Seq.averageBy for empty sequence" <| fun () ->
let xs = Seq.empty<float>
(try Seq.averageBy ((*) 2.) xs |> ignore; false with | _ -> true) |> equal true

testCase "Seq.average works" <| fun () ->
let xs = seq {1.; 2.; 3.; 4.}
Seq.average xs
Expand Down

0 comments on commit 0633c4c

Please sign in to comment.