Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use tryPick to get the first element of a sequence?

Tags:

f#

seq

I was trying to use Seq.first today, and the compiler says it has been deprecated in favor of Seq.tryPick. It says that it applies a function and returns the first result that returns Some. I guess I can just say fun x -> x!=0 since I know the first one will return Some in my case, but what is the proper constraint to put here? What is the correct syntax?

To clarify, I want to use it in the format:

let foo(x:seq<int>) =
   x.filter(fun x -> x>0)
   |> Seq.tryPick (??)
like image 344
esac Avatar asked Sep 26 '09 19:09

esac


People also ask

What is a sequence in f#?

A sequence is a logical series of elements all of one type. Sequences are particularly useful when you have a large, ordered collection of data but do not necessarily expect to use all of the elements.

What is yield in F#?

yield! (pronounced yield bang) inserts all the items of another sequence into this sequence being built. Or, in other words, it appends a sequence.

How to create an array in f#?

You can create arrays in several ways. You can create a small array by listing consecutive values between [| and |] and separated by semicolons, as shown in the following examples. You can also put each element on a separate line, in which case the semicolon separator is optional.


1 Answers

The key is that 'Seq.first' did not return the first element, rather it returned the first element that matched some 'choose' predicate:

let a = [1;2;3]
// two ways to select the first even number (old name, new name)
let r1 = a |> Seq.first (fun x -> if x%2=0 then Some(x) else None) 
let r2 = a |> Seq.tryPick (fun x -> if x%2=0 then Some(x) else None) 

If you just want the first element, use Seq.head

let r3 = a |> Seq.head 
like image 87
Brian Avatar answered Sep 18 '22 12:09

Brian