So an F# Sequence Should Stick Around For a While

If you create a sequence in Clojure, the sequence sticks around within the scope of its creation. That is, once a Clojure sequence is created and bound to a var, nothing special has to be done to make sure its contents stick around. This is not so with F#.

Take this program


open System
open System.Collections.Generic
open System.Text
open System.IO
#nowarn "40"

let rec readLines () =
    seq {
    let line = Console.ReadLine()
    if not (line.Equals("")) then
           yield Int32.Parse(line)
           yield! readLines ()
    }

[<EntryPoint>]
let main argv =
    let inSeq = readLines ()    

    inSeq

    |> Seq.length

    |> printfn "%d lines read"

    // This will keep it alive enough to read your output
    Console.ReadKey() |> ignore
    0

Because of a sequences’ inherent laziness, the reading in of numbers does not begin until inSeq’s length is computed. Without caching inSeq, you will have to read the integers in again if you want to iterate the sequence, unless this change is made


let inSeq = readLines () |> Seq.cache

Advertisements

Leave a comment

Filed under Clojure, F#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s