Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 668
user392226 Avatar asked Nov 05 '10 06:11

user392226


1 Answers

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.

like image 198
Steve Rowe Avatar answered Oct 17 '22 09:10

Steve Rowe