为什么我的Seq.map函数没有被执行?

Sco*_*rod 1 f#

我还不明白为什么我的addLink函数没有被调用.

我有以下代码:

let links =   source |> getLinks
let linkIds = links  |> Seq.map addLink // addLink never gets executed
Run Code Online (Sandbox Code Playgroud)

起初,我认为链接值是空的.

但事实并非如此.我通过调用以下内容验证了它的填充:

let count = Seq.length links // Returns over 100 items
Run Code Online (Sandbox Code Playgroud)

注意:

我能够执行该功能的唯一方法是首先执行:

let count  = linkIds |> Seq.length // Call this after performing map
Run Code Online (Sandbox Code Playgroud)

为什么我需要这样做才能调用我的函数?

附录:

let addLink (info:Link) =
    let commandFunc (command: SqlCommand) = 
        command |> addWithValue "@ProfileId"     info.ProfileId
                |> addWithValue "@Title"         info.Title
                |> addWithValue "@Description"   info.Description
                |> addWithValue "@Url"           info.Url
                |> addWithValue "@ContentTypeId" (info.ContentType |> contentTypeToId)
                |> addWithValue "@IsFeatured"    info.IsFeatured
                |> addWithValue "@Created"       DateTime.Now

    commandFunc |> execute connectionString addLinkSql


[<CLIMutable>]
type Link = { 
    Id:            int
    ProfileId:     string
    Title:         String
    Description:   String
    Url:           string
    Topics:        Topic list
    ContentType:   string
    IsFeatured:    bool
}
Run Code Online (Sandbox Code Playgroud)

这是源代码.

The*_*Fox 7

Seq<'a>是一样的IEnumerable<'a>,这是懒惰的.这意味着序列中的每个元素仅在需要时进行评估.如果你想确保调用副作用,那么你可以通过添加将它转换为像列表这样的具体数据结构Seq.toList.

但是,编写执行副作用的代码分别对返回值的代码更好,通常也可以.您可以使用一个函数计算linkIds,并使用另一个函数执行副作用Seq.iter,这会强制完全评估序列.