ca9163d9
ca9163d9

Reputation: 29159

Code in Seq.map not executed?

I have the following code. And the code between Seq.map and ignore is not executed. The two printfn are not executed. Why?

I tried to debug it and set breakpoints on

  1. links (it highlights the whole pipe),
  2. printfn "Downloading"
  3. printfn "Downloaded" in function download.

The execution will break on the first one but breakpoint 2, 3 will never be hit. (or be stepped into). Does F# optimized the Seq.map part since the result is ignored?

let download url =
    printfn "Downloaded"
    () // Will complete the function later.

let getLinks url =
    ....
    |> Seq.toList

let .....
    async {
        ......
        links = getLinks url // Tried to modify getLinks to return a list instead of seq
        ........
            links // execution hit this pipe (as a whole)
            |> Seq.map (fun l -> 
                printfn "Downloading" // execution never hit here, tried links as Seq or List
                download l) 
            |> ignore

Update: I know for in do works. Why Seq.map doesn't?

Upvotes: 2

Views: 587

Answers (1)

ildjarn
ildjarn

Reputation: 62975

As John said, seq is lazy, and because you never actually traverse the sequence (instead just discarding it via ignore), the code in the lambda you pass to Seq.map is never executed. If you change ignore to Seq.iter ignore you will traverse the sequence and see the output you desire. (Any function that necessarily traverses the sequence will work, e.g. Seq.count |> ignore.)

Upvotes: 5

Related Questions