Skip to content

Commit

Permalink
List.transpose should throw error when given jagged array (dotnet#6908)
Browse files Browse the repository at this point in the history
* transpose does not throw when one of the elements is empty
  • Loading branch information
PatrickMcDonald committed Jun 12, 2019
1 parent 027e8c9 commit 10bf1fc
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 6 deletions.
15 changes: 9 additions & 6 deletions src/fsharp/FSharp.Core/local.fs
Original file line number Diff line number Diff line change
Expand Up @@ -717,25 +717,28 @@ module internal List =
invalidArgDifferentListLength "list.[0]" (System.String.Format("list.[{0}]", j)) t.Length
[], [], 0
| h :: t ->
let mutable j = 0
for t' in tail do
j <- j + 1
if t'.IsEmpty then
invalidArgDifferentListLength (System.String.Format("list.[{0}]", j)) "list.[0]" (t.Length + 1)
let headsCons = freshConsNoTail h
let tailsCons = freshConsNoTail t
let headCount = transposeGetHeadsFreshConsTail headsCons tailsCons tail 1
headsCons, tailsCons, headCount

/// Append the next element to the transposed list
let rec transposeToFreshConsTail cons list expectedCount =
let rec transposeToFreshConsTail cons list =
match list with
| [] -> setFreshConsTail cons []
| _ ->
match transposeGetHeads list with
| [], _, _ ->
setFreshConsTail cons []
| heads, tails, headCount ->
if headCount < expectedCount then
invalidArgDifferentListLength (System.String.Format("list.[{0}]", headCount)) "list.[0]" <| tails.[0].Length + 1
| heads, tails, _ ->
let cons2 = freshConsNoTail heads
setFreshConsTail cons cons2
transposeToFreshConsTail cons2 tails expectedCount
transposeToFreshConsTail cons2 tails

/// Build the transposed list
let transpose (list: 'T list list) =
Expand All @@ -746,7 +749,7 @@ module internal List =
let heads, tails, headCount = transposeGetHeads list
if headCount = 0 then [] else
let cons = freshConsNoTail heads
transposeToFreshConsTail cons tails headCount
transposeToFreshConsTail cons tails
cons

let rec truncateToFreshConsTail cons count list =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -842,6 +842,7 @@ type ListModule02() =
// jagged lists
CheckThrowsArgumentException (fun () -> List.transpose [[1; 2]; [3]] |> ignore)
CheckThrowsArgumentException (fun () -> List.transpose [[1]; [2; 3]] |> ignore)
CheckThrowsArgumentException (fun () -> List.transpose [[1; 2]; []; [3; 4]] |> ignore)

[<Test>]
member this.Truncate() =
Expand Down

0 comments on commit 10bf1fc

Please sign in to comment.