简体   繁体   中英

How can I test if a sequence is empty in F#?

Consider this F# code which computes a factor of a number:

let n = 340339004337I

// A sequence of all factors:
let factors = seq { 1I .. n / 2I} |> Seq.filter (fun x -> n % x = 0I) 

// Pull off the first factor from the sequence:
let factor = 
    if factors = seq [] then
        n
    else
        factors |> Seq.nth 0

In other words, if factors is empty, then return n . Otherwise, pull off the first element from factors . The goal is to account for all factors between 1 and (n/2) , and n itself since 1 and n are always factors of n .

The factors = seq [] test isn't working. I arrived at this syntax by looking at this:

> seq {1 .. 100} |> Seq.filter (fun x -> false) ;;
val it : seq<int> = seq []

However, I don't think seq [] is actually an empty sequence:

> Seq.empty = seq [] ;;
val it : bool = false

How can I test if a sequence is empty?

Try Seq.isEmpty .

if Seq.isEmpty yourSeqName then doSomething else doSomethingElse

By the way, Seq.empty creates an empty Seq. It doesn't test for one.

Seq.isEmpty

http://msdn.microsoft.com/en-us/library/ee353547.aspx

The problem with your = test, I presume, is that it is comparing two different objects of type IEnumerable<int> for reference-equality.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM